Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Views.Grid

'--- Created Date On : 30-Sep-2010 (Jagdish)

Public Class frmPatientInfo
    Dim mstrMode, mstrIMode, mstrPMode, mstrAMode, mstrVMode As String
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean, blnLocked As Boolean
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged, mblnIChanged, mblnPchanged, mblnAChanged, mblnVChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnExpanded As Boolean = False
    Dim mblnAutoSize As Boolean = True
    Dim gridView1 As Views.Grid.GridView
    Dim mblnCancelDisplay As Boolean
    Public mblnFromOutside As Boolean

    Public PatientId, VisitId As Integer
    Dim Pid As Integer                  'For Cancel Button
    Dim IsThisTabPopulated() As Boolean 'Array hold true/false value showing if tab populated or not.
    Dim rpglkDiagnosis As RepositoryItemGridLookUpEdit
    Dim rpglkSeverity As RepositoryItemGridLookUpEdit
    Dim rpdtDiagnosisDate As RepositoryItemDateEdit
    Dim rpdtResolveDate As RepositoryItemDateEdit
    Dim rpglkVaccine As RepositoryItemGridLookUpEdit
    Dim rpdtVaccine As RepositoryItemDateEdit
    Dim memoMessages As RepositoryItemMemoEdit
    Dim WithEvents rptxtCost As RepositoryItemTextEdit
    Dim WithEvents rptxtTotal As RepositoryItemTextEdit
    Dim WithEvents rptxtPayment As RepositoryItemTextEdit

    Public Sub New(ByVal id As Integer)
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

        PatientId = id 'This id is used to fetch information from database 
        Pid = id        'This id is used to fetch information from database when cancel button is clicked

    End Sub

    Private Sub frmPatientInfo_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        If mblnActivate = True Then
            mblnActivate = False
            Call SetEditorDataColumn()
            Call SetEditorDataColumnForVaccination()
            If PatientId > 0 Then
                mstrMode = "Edit"
                btnAdd.Text = "&Add"
            Else
                mstrMode = "Add"
                btnAdd.Text = "&New Patient"
            End If
        End If
    End Sub

    Private Sub frmPatientInfo_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult

            If mblnChanged = True Or mblnPchanged = True Or mblnAChanged = True Or mblnIChanged = True Or mblnVChanged = True Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If mblnChanged = True Then
                        Call blnSaveRecords(0)
                        mblnChanged = False
                    End If
                    If mblnPchanged = True Then
                        Call blnSaveRecords(1)
                        mblnPchanged = False
                    End If
                    If mblnIChanged = True Then
                        Call blnSaveRecords(2)
                        mblnIChanged = False
                    End If
                    If mblnAChanged = True Then
                        Call blnSaveRecords(3)
                        mblnAChanged = False
                    End If
                    If mblnVChanged = True Then
                        Call blnSaveRecords(4)
                        mblnVChanged = False
                    End If
                    'If blnSaveRecords(xtcMain.SelectedTabPageIndex) = False Then
                    '    e.Cancel = True
                    '    blnUnload = False
                    '    Exit Sub
                    'End If
                    'mblnChanged = False
                    'mblnPchanged = False
                    'mblnIChanged = False
                    'mblnAChanged = False
                    'mblnVChanged = False
                    'mblnFromOutside = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmPatientInfo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        mblnCancelDisplay = True
        If blnKeyTrap(e.KeyCode, Me, True, grdPRecords) = True Then mblnCancelDisplay = False : Exit Sub
        mblnCancelDisplay = False
        pbRecords.Visible = False
    End Sub

    Private Sub frmPatientInfo_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())

            ReDim Preserve IsThisTabPopulated(xtcMain.TabPages.Count - 1) 'set dimension equal to number of tabs
            Call GetAccessPermission(Me, "frmPatientInfo")

            Call FillDemographicsPage(PatientId)
            IsThisTabPopulated(0) = True

            Call setPBRecords(Me, pbRecords)
            mblnActivate = True
            mblnChanged = False
            mblnPchanged = False
            mblnIChanged = False
            mblnAChanged = False
            mblnVChanged = False

            If Array.IndexOf(gstrAPForms, "frmNurseNote", 0) >= 0 Then
                btnNurseNotes.Enabled = True
            Else
                btnNurseNotes.Enabled = False
            End If

            If Array.IndexOf(gstrAPForms, "frmDoctorsNote", 0) >= 0 Then
                btnDoctorNotes.Enabled = True
            Else
                btnDoctorNotes.Enabled = False
            End If

            If gintUserLevelId = 3 Then
                grbAccount.Enabled = False
            End If
            'txtDFirstName.Focus()
            cboTitle.Focus()
            chkDecreased.Checked = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False
        If IsDBNullOrNothing(cboTitle.Text) Then
            strMsg = "Please select Title"
            cboTitle.Focus()
        ElseIf Trim(txtDFirstName.Text) = "" Then
            strMsg = "Please enter First Name."
            txtDFirstName.Focus()
        ElseIf Trim(txtDLastName.Text) = "" Then
            strMsg = "Please enter Last Name."
            txtDLastName.Focus()
        ElseIf IsDBNullOrNothing(lkDTown.EditValue) Then
            strMsg = "Please select Town."
            lkDTown.Focus()

        ElseIf IsDBNullOrNothing(lkDCountry.EditValue) Then
            strMsg = "Please select Country."
            lkDCompany.Focus()
        ElseIf IsDBNullOrNothing(lkDGender.EditValue) Then
            strMsg = "Please select Gender."
            lkDGender.Focus()
        ElseIf IsDBNullOrNothing(lkDMaritalStatus.EditValue) Then
            strMsg = "Please select Marital Status."
            lkDMaritalStatus.Focus()
        End If


        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidEntry = True
        End If
    End Function

    Private Function blnSaveRecords(ByVal TabId As Integer) As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String = ""
        Try
            blnSaveRecords = False

            If IsValidEntry() = False Then
                Exit Function
            End If

            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " this " & xtcMain.SelectedTabPage.Text & " details?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            blnSaveRecords = True

            If TabId = 0 Then              'Demographics
                If mstrMode = "Add" Then
                    If IsRepeatPatient(txtDFirstName.Text, txtDLastName.Text, txtDMiddleName.Text, dtDDOB) Then
                        If MessageBox.Show("Patient with similar name and birthdate already exists." & vbCrLf & "Do you want to continue?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
                            Exit Function
                        End If
                    End If
                    strQuery = Trim(SmartReplace(txtDFirstName.Text) & "") & ""
                    If IsDBNullOrNothing(txtDMiddleName.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & Trim(SmartReplace(txtDMiddleName.Text) & "") & ""
                    End If
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDLastName.Text) & "") & ""
                    strQuery = strQuery & "," & Val(lkDGender.EditValue)
                    strQuery = strQuery & "," & Val(lkDMaritalStatus.EditValue)
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDStreetAddress1.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDStreetAddress2.Text) & "") & ""
                    strQuery = strQuery & "," & Val(lkDParish.EditValue)
                    strQuery = strQuery & "," & Val(lkDTown.EditValue)
                    strQuery = strQuery & "," & Val(lkDCountry.EditValue)
                    If IsDBNullOrNothing(lkDCompany.EditValue) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & Val(lkDCompany.EditValue)
                    End If
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDPolicyNo.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDInsuredName.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDOccupation.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDWorkPhone.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDHomePhone.Text) & "") & ""
                    If IsDBNullOrNothing(dtDDOB.EditValue) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & ",'" & Format(CDate(dtDDOB.EditValue), gstrDtFormat) & "'"
                    End If
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDKinName.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDKinPhone.Text) & "") & ""
                    strQuery = strQuery & "," & Trim(SmartReplace(txtDKinOccupation.Text) & "") & "" & _
                     ",NUll,0"
                    If chkDecreased.Checked = True Then
                        strQuery = strQuery & ",1"
                        strQuery = strQuery & ",'" & Format(dtDeathDate.EditValue, "MM/dd/yyyy") & "'"
                        strQuery = strQuery & "," & lkCauseOfDeath.EditValue
                    Else
                        strQuery = strQuery & ",0"
                        strQuery = strQuery & ",Null,Null"
                    End If
                    strQuery = strQuery & "," & SmartReplace(cboTitle.Text)
                    Call InsertintoTable("tblPatientInfo", strQuery)
                    PatientId = GetId("tblPatientInfo")

                Else
                    strQuery = "FirstName=" & Trim(SmartReplace(txtDFirstName.Text) & "") & "" & _
                                ",MiddleName=" & Trim(SmartReplace(txtDMiddleName.Text) & "") & "" & _
                                ",LastName=" & Trim(SmartReplace(txtDLastName.Text) & "") & "" & _
                                ",SexId=" & Val(lkDGender.EditValue) & _
                                ",MaritalStatusId=" & Val(lkDMaritalStatus.EditValue) & _
                                ",Address1=" & Trim(SmartReplace(txtDStreetAddress1.Text) & "") & "" & _
                                ",Address2=" & Trim(SmartReplace(txtDStreetAddress2.Text) & "") & "" & _
                                ",ParishId=" & Val(lkDParish.EditValue) & _
                                ",TownId=" & Val(lkDTown.EditValue) & _
                                ",CountryId=" & Val(lkDCountry.EditValue) & _
                                ",InsuranceCompanyId=" & IIf(IsDBNullOrNothing(lkDCompany.EditValue), "Null", Val(lkDCompany.EditValue)) & _
                                ",InsuranceNumber=" & Trim(SmartReplace(txtDPolicyNo.Text) & "") & "" & _
                                ",InsuranceName=" & Trim(SmartReplace(txtDInsuredName.Text) & "") & "" & _
                                ",Occupation=" & Trim(SmartReplace(txtDOccupation.Text) & "") & "" & _
                                ",WorkPhone=" & Trim(SmartReplace(txtDWorkPhone.Text) & "") & "" & _
                                ",HomePhone=" & Trim(SmartReplace(txtDHomePhone.Text) & "") & "" & _
                                ",NextOfKinName=" & Trim(SmartReplace(txtDKinName.Text) & "") & "" & _
                                ",NextOfKinPhone=" & Trim(SmartReplace(txtDKinPhone.Text) & "") & "" & _
                                ",NextOfKinOccupation=" & Trim(SmartReplace(txtDKinOccupation.Text) & "") & "" & _
                                ",PatientTitle=" & SmartReplace(cboTitle.Text)
                    If IsDBNullOrNothing(dtDDOB.EditValue) Then
                        strQuery = strQuery & ",DateOfBirth=Null"
                    Else
                        strQuery = strQuery & ",DateOfBirth=" & IIf(IsDBNullOrNothing(CDate(dtDDOB.EditValue)), "Null", "'" & Format(CDate(dtDDOB.EditValue), gstrDtFormat) & "'")
                    End If
                    If chkDecreased.Checked = True Then
                        strQuery = strQuery & ",IsDecreased=1"
                        strQuery = strQuery & ",DateOfDeath='" & Format(CDate(dtDeathDate.EditValue), "MM/dd/yyyy") & "'"
                        strQuery = strQuery & ",CauseId=" & Val(lkCauseOfDeath.EditValue)
                    Else
                        strQuery = strQuery & ",IsDecreased=0"
                        strQuery = strQuery & ",DateOfDeath=Null"
                        strQuery = strQuery & ",CauseId=Null"
                    End If
                    Call UpdateTable("tblPatientInfo", strQuery, "PatientId=" & PatientId & " and Void=0")
                End If
                mblnChanged = False
            ElseIf TabId = 1 Then                 'Past Visit Details
                If mstrPMode = "Add" Then
                    strQuery = PatientId & _
                                "," & GetPracticeId(gintUserID) & _
                                ",'" & Format(CDate(dtPVisitDate.EditValue), gstrDtFormat) & "'" & _
                                "," & Val(lkPVisitLocation.EditValue) & _
                                ",1" & _
                                "," & Trim(SmartReplace(txtPComplaint.Text) & "") & "" & _
                                ",Null,Null,0" & _
                                "," & Trim(SmartReplace(txtPTherapy.Text) & "") & "" & _
                                "," & PatientStatus.VisitComplete & _
                                ",Null,1"
                    Call InsertintoTable("tblVisits", strQuery)
                    VisitId = GetId("tblVisits")

                    strQuery = "" & Trim(SmartReplace(txtPTherapy.Text) & "") & "" & _
                                ",1" & _
                                "," & VisitId & _
                                ",Null,Null,Null,Null"
                    Call InsertintoTable("tblVisitResult", strQuery)

                Else
                    strQuery = " VisitLocationId=" & Val(lkPVisitLocation.EditValue) & _
                                ",AppointmentTypeId=1" & _
                                ",PresentingComplaint=" & Trim(SmartReplace(txtPComplaint.Text) & "") & "" & _
                                ",Therapy=" & Trim(SmartReplace(txtPTherapy.Text) & "")
                    Call UpdateTable("tblVisits", strQuery, "VisitId=" & VisitId)
                End If

                Call DeleteFromTable("tblVisitDiagnosis", "VisitId=" & VisitId)
                For intCtr As Integer = 0 To gdvPDiagnosis.RowCount - 1
                    If Val(Trim(gdvPDiagnosis.GetRowCellValue(intCtr, "Diagnosis") & "")) <= 0 Then Continue For
                    strQuery = Val(gdvPDiagnosis.GetRowCellValue(intCtr, "Diagnosis"))
                    strQuery = strQuery & ",'" & strRecordID("LtblDiagnosis", "Diagnosis", "DiagnosisId=" & Val(gdvPDiagnosis.GetRowCellValue(intCtr, "Diagnosis"))) & "'"
                    strQuery = strQuery & "," & Val(gdvPDiagnosis.GetRowCellValue(intCtr, "Severity"))
                    strQuery = strQuery & "," & VisitId
                    strQuery = strQuery & ",'" & Format(gdvPDiagnosis.GetRowCellValue(intCtr, "DiagnosisDate"), gstrDtFormat) & "'"
                    If Val(gdvPDiagnosis.GetRowCellValue(intCtr, "Active").ToString) <= 0 Then
                        strQuery = strQuery & ",0"
                    Else
                        strQuery = strQuery & "," & Val(gdvPDiagnosis.GetRowCellValue(intCtr, "Active"))
                    End If

                    If IsDBNullOrNothing(gdvPDiagnosis.GetRowCellValue(intCtr, "ResolveDate")) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & ",'" & Format(gdvPDiagnosis.GetRowCellValue(intCtr, "ResolveDate"), gstrDtFormat) & "'"
                    End If
                    Call InsertintoTable("tblVisitDiagnosis", strQuery)
                Next
                mblnPchanged = False
            ElseIf TabId = 2 Then     'Images
                If mstrIMode = "Add" Then
                    strQuery = PatientId & "," & Trim(SmartReplace(txtIName.Text) & "") & "" & _
                          "," & Trim(SmartReplace(txtIFullPath.Text) & "") & "" & _
                          "," & Trim(SmartReplace(txtIDescription.Text) & "") & "" & _
                          "," & Trim(SmartReplace(txtIComments.Text) & "") & "" & _
                          "," & Val(lkIImageType.EditValue)
                    Call InsertintoTable("tblPatientsImages", strQuery)
                Else
                    strQuery = "ImageName=" & Trim(SmartReplace(txtIName.Text) & "") & "" & _
                           ",ImagePath=" & Trim(SmartReplace(txtIFullPath.Text) & "") & "" & _
                           ",Description=" & Trim(SmartReplace(txtIDescription.Text) & "") & "" & _
                           ",Comments=" & Trim(SmartReplace(txtIComments.Text) & "") & "" & _
                           ",ImageTypeId=" & Val(lkIImageType.EditValue)
                    Call UpdateTable("tblPatientsImages", strQuery, "ImageId=" & gdvIRecords.GetRowCellValue(gdvIRecords.FocusedRowHandle, "ImageId"))
                End If
                mblnIChanged = False
            ElseIf TabId = 3 Then           'Accounts
                If mstrAMode = "Add" Then
                    Dim CheckId As Integer

                    If Val(lkAPaymentType.EditValue) = 4 OrElse Val(lkAPaymentType.EditValue) = 8 Then
                        InsertUpdateCheckData(CheckId, True)
                    End If

                    strQuery = PatientId & _
                                "," & Val(lkAPaymentType.EditValue) & _
                                "," & GetPracticeId(gintUserID) & _
                                ",'" & Format(CDate(dtPaymentDate.EditValue), gstrDtFormat) & "'" & _
                                "," & Val(txtAPayment.Text) & _
                                "," & IIf(IsDBNullOrNothing(lkAInsuranceCompany.EditValue), "Null", Val(lkAInsuranceCompany.EditValue)) & _
                                "," & CheckId & _
                                "," & gintPaymentUserID
                    Call InsertintoTable("tblPayment", strQuery)
                Else
                    Dim CheckId As Integer
                    If Val(lkAPaymentType.EditValue) = 4 OrElse Val(lkAPaymentType.EditValue) = 8 Then
                        InsertUpdateCheckData(CheckId, True)
                    End If

                    strQuery = "PaymentTypeId=" & Val(lkAPaymentType.EditValue) & _
                                ",PracticeId=" & GetPracticeId(gintUserID) & _
                                ",PaymentDate='" & Format(CDate(dtPaymentDate.EditValue), gstrDtFormat) & "'" & _
                                ",Payment=" & Val(txtAPayment.Text) & _
                                ",InsuranceCompanyId=" & IIf(IsDBNullOrNothing(lkAInsuranceCompany.EditValue), "Null", Val(lkAInsuranceCompany.EditValue)) & _
                                ",CheckId=" & CheckId & _
                                ",UserId=" & gintPaymentUserID
                    Call UpdateTable("tblPayment", strQuery, "PaymentId=" & PaymentId)
                End If
                mblnAChanged = False
            ElseIf TabId = 4 Then
                Call DeleteFromTable("tblPatientImmunisationHistory", "PatientId=" & PatientId)
                For intCtr As Integer = 0 To gdvVaccinationHistory.RowCount - 1
                    If Val(Trim(gdvVaccinationHistory.GetRowCellValue(intCtr, "Vaccine") & "")) <= 0 Then Continue For
                    strQuery = PatientId & _
                                ",'" & Format(gdvVaccinationHistory.GetRowCellValue(intCtr, "Date"), gstrDtFormat) & "'" & _
                                "," & Val(gdvVaccinationHistory.GetRowCellValue(intCtr, "Vaccine"))
                    Call InsertintoTable("tblPatientImmunisationHistory", strQuery)
                Next
                mblnVChanged = False
            End If

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Function

    Private Function IsRepeatPatient(ByRef FirstName As String, ByRef LastName As String, ByRef MiddleName As String, ByRef dtpDateOfBirth As DevExpress.XtraEditors.DateEdit) As Boolean
        Try
            Dim DoctorCriteria As String = ""

            If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
                DoctorCriteria = " AND PracticeId=" & GetPracticeId(gintUserID)
            End If

            Dim strQuery As String = "SELECT  COUNT(tblPatientInfo.PatientId) as [ID] FROM tblPatientInfo  INNER JOIN tblVisits ON " & _
                                     "tblPatientInfo.PatientId=tblVisits.PatientId  WHERE  FirstName = '" & FirstName & "' AND " & _
                                     "MiddleName='" & MiddleName & "'  AND  LastName = '" & LastName & "'"
            If Not IsDBNullOrNothing(dtDDOB.EditValue) Then
                strQuery = strQuery & " And DateOfBirth='" & Format(CDate(dtDDOB.EditValue), gstrDtFormat) & "'"
            End If
            strQuery = strQuery & DoctorCriteria
            Dim dsTemp As DataSet = FillDataSet(strQuery)

            Return IIf(dsTemp.Tables(0).Rows(0).Item("ID") > 0, True, False)

        Catch ex As Exception

        End Try
    End Function

    Private Sub txtFirstName_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDFirstName.GotFocus, txtDMiddleName.GotFocus
        sender.SelectAll()
    End Sub

    Private Sub FillDemographicsPage(ByVal PId As Integer)

        'Demogrpahics tab
        Try
            'Populate Town combo box
            Call PopulateLookupDX(lkDTown, "Town", "TownId", "LtblTown", "TownId,Town", , "Town")

            'Populate Parish combo box
            Call PopulateLookupDX(lkDParish, "Parish", "ParishId", "LtblParish", "ParishId,Parish", , "Parish")

            'Populate Country combo box
            Call PopulateLookupDX(lkDCountry, "Country", "CountryId", "LtblCountry", "CountryId,Country", , "Country")

            'Populate Gender combo box
            Call PopulateLookupDX(lkDGender, "Sex", "SexId", "LtblSex", "SexId,Sex", , "Sex")

            'Populate MaritalStatus combo box
            Call PopulateLookupDX(lkDMaritalStatus, "MaritalStatus", "MaritalStatusId", "LtblMaritalStatus", "MaritalStatusId,MaritalStatus", , "MaritalStatus")

            'Populate (Insurance) company combo box
            Call PopulateLookupDX(lkDCompany, "InsuranceCompany", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany", , "InsuranceCompany")

            'Populate Cause of Death Lookup
            Call PopulateLookupDX(lkCauseOfDeath, "Cause Of Death", "CauseId", "LtblCauseOfDeath", "CauseId,Cause [Cause Of Death]", , "Cause")

            Dim dsTemp As DataSet = FillDataSet("Select * from tblPatientInfo WHERE PatientID=" & PId & " and Void=0")
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtDFirstName.Text = Trim(.Rows(0).Item("FirstName") & "")
                    txtDMiddleName.Text = Trim(.Rows(0).Item("MiddleName") & "")
                    txtDLastName.Text = Trim(.Rows(0).Item("LastName") & "")
                    lkDGender.EditValue = CInt(.Rows(0).Item("SexId"))
                    lkDMaritalStatus.EditValue = CInt(.Rows(0).Item("MaritalStatusId"))
                    txtDStreetAddress1.Text = Trim(.Rows(0).Item("Address1") & "")
                    txtDStreetAddress2.Text = Trim(.Rows(0).Item("Address2") & "")
                    lkDTown.EditValue = CInt(Val(.Rows(0).Item("TownId")))
                    lkDParish.EditValue = CInt(Val(.Rows(0).Item("ParishId")))
                    lkDCountry.EditValue = CInt(Val(.Rows(0).Item("CountryId")))
                    If IsDBNullOrNothing(.Rows(0).Item("InsuranceCompanyId")) Then
                        lkDCompany.EditValue = Nothing
                    Else
                        lkDCompany.EditValue = CInt(.Rows(0).Item("InsuranceCompanyId"))
                    End If
                    txtDPolicyNo.Text = Trim(.Rows(0).Item("InsuranceNumber") & "")
                    txtDInsuredName.Text = Trim(.Rows(0).Item("InsuranceName") & "")
                    txtDOccupation.Text = Trim(.Rows(0).Item("Occupation") & "")
                    txtDWorkPhone.Text = Trim(.Rows(0).Item("WorkPhone") & "")
                    txtDHomePhone.Text = Trim(.Rows(0).Item("HomePhone") & "")
                    If IsDBNullOrNothing(.Rows(0).Item("DateOfBirth")) Then
                        dtDDOB.EditValue = Nothing
                    Else
                        dtDDOB.EditValue = Format(.Rows(0).Item("DateOfBirth"), "MMM dd,yyyy")
                        If DateDiff(DateInterval.Year, dtDDOB.EditValue, Today) <> 0 Then
                            lblAgeInformation.Text = "Patient is " & DateDiff(DateInterval.Year, dtDDOB.EditValue, Today) & " Years." 'show the age of patient
                        Else
                            lblAgeInformation.Text = "Patient is " & DateDiff(DateInterval.Month, dtDDOB.EditValue, Today) & " Months."
                        End If
                    End If
                    txtDKinName.Text = Trim(.Rows(0).Item("NextOfKinName") & "")
                    txtDKinPhone.Text = Trim(.Rows(0).Item("NextOfKinPhone") & "")
                    txtDKinOccupation.Text = Trim(.Rows(0).Item("NextOfKinOccupation") & "")
                    chkDecreased.Checked = .Rows(0).Item("IsDecreased")
                    If IsDBNullOrNothing(.Rows(0).Item("DateOfDeath")) Then
                        dtDeathDate.EditValue = Nothing
                    Else
                        dtDeathDate.EditValue = Format(.Rows(0).Item("DateOfDeath"), "MM/dd/yyyy")
                    End If
                    If IsDBNullOrNothing(.Rows(0).Item("CauseId")) Then
                        lkCauseOfDeath.EditValue = Nothing
                    Else
                        lkCauseOfDeath.EditValue = CInt(.Rows(0).Item("CauseId"))
                    End If
                    cboTitle.Text = Trim(.Rows(0).Item("PatientTitle") & "")
                End With
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub xtcMain_SelectedPageChanged(ByVal sender As Object, ByVal e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles xtcMain.SelectedPageChanged
        Try
            'if new patient is not added then dont allow to navigate other tab
            If PatientId = -1 Then
                If xtcMain.SelectedTabPage Is xtpAccount OrElse xtcMain.SelectedTabPage Is xtpImage OrElse xtcMain.SelectedTabPage Is xtpPastVisits OrElse xtcMain.SelectedTabPage Is xtpVaccinationRecord Then
                    MessageBox.Show("Please add patient.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    xtcMain.SelectedTabPage = xtpDemographics
                End If
            End If

            'following if else is used to fill the tabs when they get selected first time.
            If xtcMain.SelectedTabPage Is xtpImage Then
                If Not IsThisTabPopulated(xtcMain.SelectedTabPageIndex) Then
                    FillImageTab()
                    IsThisTabPopulated(xtcMain.SelectedTabPageIndex) = True
                    mblnIChanged = False
                End If
                txtIName.Focus()
            ElseIf xtcMain.SelectedTabPage Is xtpAccount Then
                If gintUserLevelId <> 3 Then
                    If Array.IndexOf(gstrAPForms, "frmChargeAndPayment", 0) >= 0 Then
                        grbPayments.Enabled = False
                        If Not IsThisTabPopulated(xtcMain.SelectedTabPageIndex) Then
                            FillAccountTab()
                            IsThisTabPopulated(xtcMain.SelectedTabPageIndex) = True
                            mblnAChanged = False
                        End If
                        lkAPaymentType.Focus()
                    Else
                        xtcMain.SelectedTabPage = xtpDemographics
                        cboTitle.Focus()
                    End If
                Else
                    xtcMain.SelectedTabPage = xtpDemographics
                    cboTitle.Focus()
                End If

            ElseIf xtcMain.SelectedTabPage Is xtpPastVisits Then
                If Array.IndexOf(gstrAPForms, "frmNurseNote", 0) >= 0 And Array.IndexOf(gstrAPForms, "frmDoctorsNote", 0) >= 0 Then
                    If Not IsThisTabPopulated(xtcMain.SelectedTabPageIndex) Then
                        Call InitialiseDataEntry()
                        FillPastVisitsTab()
                        IsThisTabPopulated(xtcMain.SelectedTabPageIndex) = True
                        mblnPchanged = False
                    End If
                    If gdvPRecords.RowCount > 0 Then
                        Call gdvPRecords_FocusedRowChanged(Nothing, Nothing)
                    End If
                    dtPVisitDate.Focus()
                Else
                    xtcMain.SelectedTabPage = xtpDemographics
                    cboTitle.Focus()
                End If
                
            ElseIf xtcMain.SelectedTabPage Is xtpVaccinationRecord Then
                If Not IsThisTabPopulated(xtcMain.SelectedTabPageIndex) Then
                    Call InitialiseDataEntryForVaccination()
                    FillVaccinationTab()
                    IsThisTabPopulated(xtcMain.SelectedTabPageIndex) = True
                    mblnVChanged = False
                End If
                gdvVaccinationHistory.Focus()
                gdvVaccinationHistory.FocusedColumn = gdvVaccinationHistory.VisibleColumns(0)
                gdvVaccinationHistory.ShowEditor()
            ElseIf xtcMain.SelectedTabPage Is xtpDemographics Then
                cboTitle.Focus()
                mblnChanged = False
            ElseIf xtcMain.SelectedTabPage Is xtpTaskAndMessages Then
                If Not IsThisTabPopulated(xtcMain.SelectedTabPageIndex) Then
                    FillTaskMessagesGrid()
                    IsThisTabPopulated(xtcMain.SelectedTabPageIndex) = True
                End If
            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub FillVaccinationTab()
        'Vaccination tab

        FillVaccinationTemplateGrid()
        ''popualte vaccination history
        If PatientId > 0 Then
            FillVaccinationHistoryGrid()
        End If


    End Sub

    Private Sub FillVaccinationTemplateGrid()
        ''Populate gdvVaccinationTemplate
        Dim dsTemp As DataSet = FillDataSet("Select SequenceId,Sequence,Vaccine,ReceiveAge from tblImmunisationTemplate")
        With grdVaccinationTemplate
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
        dsTemp.Dispose()
        With gdvVaccinationTemplate
            .Columns("SequenceId").Visible = False
        End With

    End Sub

    Private Sub FillVaccinationHistoryGrid()
        Call SetEditorDataColumnForVaccination()
        Dim dsTemp As DataSet

        dsTemp = FillDataSet("Select ImmunisationId [ID],PatientId,ImmunisationDate [Date],VaccineId [Vaccine] from tblPatientImmunisationHistory where PatientId=" & PatientId)
        With grdVaccinationHistory
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With

        dsTemp.Dispose()
        With gdvVaccinationHistory
            .Columns("ID").Visible = False
            .Columns("PatientId").Visible = False
            '.Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTim
            '.Columns("Date").DisplayFormat.FormatString = gstrDtFormat
        End With

    End Sub


    Private Sub InitialiseDataEntryForVaccination()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("Vaccination")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("PatientId", GetType(Integer))
            .Add("Date", GetType(Date))
            .Add("Vaccine", GetType(Integer))
        End With
        grdVaccinationHistory.DataSource = dtTemp
        gdvVaccinationHistory.Columns("ID").Visible = False
        gdvVaccinationHistory.Columns("PatientId").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetEditorDataColumnForVaccination()
        Try
            Call InitialiseDataEntryForVaccination()
            Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvVaccinationHistory
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                .Columns("PatientId").Visible = False
                .Columns("PatientId").OptionsColumn.ShowInCustomizationForm = False
                .Columns("Vaccine").AppearanceHeader.Font = fnBold
                .Columns("Vaccine").Width = 150

                .Columns("Date").AppearanceHeader.Font = fnBold
                '.Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                '.Columns("Date").DisplayFormat.FormatString = gstrDtFormat
                .Columns("Date").Width = 100
                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpglkVaccine = New RepositoryItemGridLookUpEdit()
            Dim VaccineNameSize As Size
            VaccineNameSize.Width = 500
            VaccineNameSize.Height = 40
            Dim dsTemp As DataSet = FillDataSet("select VaccineId,Vaccine from tblVaccine order by Vaccine")
            With rpglkVaccine
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "Vaccine"
                .ValueMember = "VaccineId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("VaccineId").Visible = False
                .PopupFormMinSize = VaccineNameSize

            End With
            dsTemp.Dispose()
            rpdtVaccine = New RepositoryItemDateEdit
            With rpdtVaccine
                '.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Custom
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .EditFormat.FormatString = gstrDtFormat
                '.Mask.UseMaskAsDisplayFormat = True
            End With

            grdVaccinationHistory.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpglkVaccine, rpdtVaccine})
            With gdvVaccinationHistory
                .Columns("Vaccine").ColumnEdit = rpglkVaccine
                '.Columns("Stock").ColumnEdit = rptxtStock
                .Columns("Date").ColumnEdit = rpdtVaccine
                '.Columns("Remarks").ColumnEdit = rptxtremarks
                '.OptionsView.ShowFooter = True
                ' .Columns("Diagnosis").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
            'If lkDepartment.EditValue = strRecordID("master_department", "record_id", "dept_name='STORE'") Then
            '  gdvDataEntry.Columns("Stock").Visible = True
            'Else
            '  gdvDataEntry.Columns("Stock").Visible = False
            'End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillPastVisitsTab()

        'populate combos on this tab
        Call PopulateLookupDX(lkPVisitLocation, "VisitLocation", "VisitLocationId", "LtblVisitLocation", "VisitLocationId, VisitLocation", , "VisitLocation")
        Call PastVisitGridLoad()

        '' ''dsTemp.Dispose()

        '' ''dsTemp = FillDataSet("SELECT tblVisitDiagnosis.DiagnosisId, tblVisitDiagnosis.Diagnosis, tblVisitDiagnosis.DiagnosisSeverityId, tblVisitDiagnosis.DiagnosisDate, tblVisitDiagnosis.Active, tblVisitDiagnosis.ResolveDate, LtblDiagnosisSeverity.DiagnosisSeverity FROM  tblVisitDiagnosis INNER JOIN LtblDiagnosisSeverity ON tblVisitDiagnosis.DiagnosisSeverityId = LtblDiagnosisSeverity.DiagnosisSeverityId WHERE VisitId=" & Val(gdvPRecords.GetRowCellValue(gdvPRecords.FocusedRowHandle, "VisitId")))
        '' ''With grdPDiagnosis
        '' ''    .BeginUpdate()
        '' ''    .DataSource = dsTemp.Tables(0)
        '' ''    .EndUpdate()
        '' ''End With
        ''create tablestyle for dianosis grid   DiagnosisId, Diagnosis, DiagnosisSeverityId, DiagnosisDate, Active, ResolveDate
        'Dim stlDiagnosis As DataGridTableStyle = CreateTableStyle(New ColumnInfo("DiagnosisId", "", 0), New ColumnInfo("Diagnosis", "Diagnosis", 120), New ColumnInfo("DiagnosisSeverityId", "Severity", 0), New ColumnInfo("DiagnosisSeverity", "Severity", 100), New ColumnInfo("DiagnosisDate", "Diagnosed", 50), New ColumnInfo("Active", "Active", 50, True), New ColumnInfo("ResolveDate", "Resolved", 50)) ', New ColumnInfo("NewRow", "", 0))

        ''Add tablestyle
        'dgdDiagnosis.TableStyles.Add(stlDiagnosis)
        'dgdDiagnosis.ReadOnly = True

        'If dgdVisits.VisibleRowCount <> 0 Then 'if there is visit then only show diagnosis.
        '    PopulateDiagnosisGrid(dgdVisits.Item(dgdVisits.CurrentRowIndex, 0)) 'argument is VisitId
        'End If

        'set Max VisitDate as todays.
        dtPVisitDate.EditValue = Format(Today, gstrDtFormat) & " " & Format(Today, "hh:mm tt")
    End Sub

    Private Sub PastVisitGridLoad()
        Dim dsTemp As DataSet
        dsTemp = FillDataSet("SELECT VisitId,VisitDate [Date],VisitLocationId,PresentingComplaint [Presenting Complaint] FROM  tblVisits WHERE PatientId = " & PatientId & " ORDER BY VisitDate")

        With grdPRecords
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
        With gdvPRecords
            .Columns("VisitId").Visible = False
            .Columns("VisitLocationId").Visible = False
            .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
            .Columns("Date").DisplayFormat.FormatString = "yyyy/MM/dd"
        End With
    End Sub

    Private Sub InitialiseDataEntry()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("Diagnosis")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("Diagnosis", GetType(Integer))
            .Add("Severity", GetType(Integer))
            .Add("VisitId", GetType(Integer))
            .Add("DiagnosisDate", GetType(Date))
            .Add("Active", GetType(Boolean))
            .Add("ResolveDate", GetType(Date))
        End With
        grdPDiagnosis.DataSource = dtTemp
        gdvPDiagnosis.Columns("ID").Visible = False
        gdvPDiagnosis.Columns("VisitId").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetEditorDataColumn()
        Try
            Call InitialiseDataEntry()
            Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvPDiagnosis
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                .Columns("VisitId").Visible = False
                .Columns("VisitId").OptionsColumn.ShowInCustomizationForm = False
                '.Columns("Diagnosis").AppearanceHeader.Font = fnBold
                .Columns("Diagnosis").Width = 100

                '.Columns("DiagnosisDate").AppearanceHeader.Font = fnBold
                .Columns("DiagnosisDate").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("DiagnosisDate").DisplayFormat.FormatString = gstrDtFormat
                .Columns("DiagnosisDate").Width = 100

                .Columns("ResolveDate").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("ResolveDate").DisplayFormat.FormatString = gstrDtFormat
                .Columns("ResolveDate").Width = 100
                .Columns("Active").Width = 50
                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpglkDiagnosis = New RepositoryItemGridLookUpEdit()
            Dim DiagnosisNameSize As Size
            DiagnosisNameSize.Width = 500
            DiagnosisNameSize.Height = 40
            Dim dsTemp As DataSet = FillDataSet("select DiagnosisId,Diagnosis,DiagnosisNumber from LtblDiagnosis order by Diagnosis")
            With rpglkDiagnosis
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "Diagnosis"
                .ValueMember = "DiagnosisId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DiagnosisId").Visible = False
                .View.Columns("DiagnosisNumber").Visible = False
                .PopupFormMinSize = DiagnosisNameSize

            End With
            dsTemp.Dispose()

            rpglkSeverity = New RepositoryItemGridLookUpEdit()
            Dim SeverityNameSize As Size
            SeverityNameSize.Width = 500
            SeverityNameSize.Height = 40
            Dim dsTemp1 As DataSet = FillDataSet("select DiagnosisSeverityId,DiagnosisSeverity from LtblDiagnosisSeverity order by DiagnosisSeverity")
            With rpglkSeverity
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp1.Tables(0)
                .DisplayMember = "DiagnosisSeverity"
                .ValueMember = "DiagnosisSeverityId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DiagnosisSeverityId").Visible = False
                .PopupFormMinSize = SeverityNameSize

            End With
            dsTemp.Dispose()

            rpdtDiagnosisDate = New RepositoryItemDateEdit
            With rpdtDiagnosisDate
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .EditFormat.FormatString = gstrDtFormat
                .Mask.UseMaskAsDisplayFormat = True
            End With

            rpdtResolveDate = New RepositoryItemDateEdit
            With rpdtResolveDate
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .EditFormat.FormatString = gstrDtFormat
                .Mask.UseMaskAsDisplayFormat = True
            End With

            grdPDiagnosis.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpglkDiagnosis, rpglkSeverity, rpdtDiagnosisDate, rpdtResolveDate})
            With gdvPDiagnosis
                .Columns("Diagnosis").ColumnEdit = rpglkDiagnosis
                '.Columns("Stock").ColumnEdit = rptxtStock
                .Columns("Severity").ColumnEdit = rpglkSeverity
                .Columns("DiagnosisDate").ColumnEdit = rpdtDiagnosisDate
                .Columns("ResolveDate").ColumnEdit = rpdtResolveDate
                '.Columns("Remarks").ColumnEdit = rptxtremarks
                '.OptionsView.ShowFooter = True
                ' .Columns("Diagnosis").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
            'If lkDepartment.EditValue = strRecordID("master_department", "record_id", "dept_name='STORE'") Then
            '  gdvDataEntry.Columns("Stock").Visible = True
            'Else
            '  gdvDataEntry.Columns("Stock").Visible = False
            'End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillAccountTab()
        'Account tab
        Try
            Dim dsTemp As DataSet
            If gintUserID <> 1 Then
                btnAccountDelete.Enabled = False
                btnAccountUpdate.Enabled = False
            End If

            'populate select practice combo
            Call PopulateLookupDX(lkASelectPractice, "Name", "PracticeId", "tblPracticeInfo JOIN vwUserDetails ON tblPracticeInfo.UserId=vwUserDetails.UserId", "PracticeId,FullName [Name]", , "[Name]")

            'if doctor is logged in then hide combo for selecting doctor
            If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
                lkASelectPractice.EditValue = GetPracticeId(gintUserID)
                lkASelectPractice.Enabled = False
            End If

            'Populate insuranceCompany Combo
            Call PopulateLookupDX(lkAInsuranceCompany, "InsuranceCompany", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany", , "InsuranceCompany", True)

            'Populate PaymenttypeCombo
            Call PopulateLookupDX(lkAPaymentType, "PaymentType", "PaymentTypeId", "LtblPaymentType", "PaymentTypeId,PaymentType", , "PaymentType")

            FillChargesGrid()
            FillPaymentGrid()

            CalCulateChargePayment()

            'show next appointment to be scheduled.
            lblANextAppointment.Visible = False
            dtANextAppointment.Visible = False

            dsTemp = FillDataSet("SELECT NextAppointmentDate FROM tblVisits WHERE (VisitId =(SELECT MAX(visitid) FROM tblvisits WHERE patientid =" & PatientId & "))")
            If dsTemp.Tables(0).Rows.Count > 0 Then
                If Not IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("NextAppointmentDate")) Then
                    dtANextAppointment.EditValue = dsTemp.Tables(0).Rows(0).Item("NextAppointmentDate")
                    lblANextAppointment.Visible = True
                    dtANextAppointment.Visible = True
                End If
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Sub FillChargesGrid()
        'populate grid
        Dim DoctorCriteria As String
        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
            DoctorCriteria = " AND tblVisits.PracticeId=" & GetPracticeId(gintUserID) & " "
        Else
            DoctorCriteria = String.Empty
        End If
        Dim dsTemp As DataSet
        dsTemp = FillDataSet("SELECT ChargeId, tblCharges.VisitId as IdVisit,VisitDate, ProcedureTypeId,ProcedureName, Quantity,tblCharges.Cost as Cost,tblCharges.Cost * Quantity AS Total FROM tblVisits JOIN ( tblCharges JOIN tblProcedures ON  tblCharges.ProcedureTypeId=tblProcedures.ProcedureId ) ON tblVisits.VisitId=tblCharges.VisitId WHERE tblVisits.PatientId=" & PatientId & DoctorCriteria)
        With grdACharges
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
        rptxtCost = New RepositoryItemTextEdit
        rptxtCost.Mask.MaskType = Mask.MaskType.Numeric
        rptxtCost.Mask.EditMask = "c2"
        rptxtCost.Mask.UseMaskAsDisplayFormat = True

        rptxtTotal = New RepositoryItemTextEdit
        rptxtTotal.Mask.MaskType = Mask.MaskType.Numeric
        rptxtTotal.Mask.EditMask = "c2"
        rptxtTotal.Mask.UseMaskAsDisplayFormat = True

        grdACharges.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rptxtCost, rptxtTotal})
        With gdvACharges
            .Columns("ChargeId").Visible = False
            .Columns("IdVisit").Visible = False
            .Columns("ProcedureTypeId").Visible = False
            .Columns("Cost").ColumnEdit = rptxtCost
            .Columns("Total").ColumnEdit = rptxtTotal
        End With
        dsTemp.Dispose()


        'Create tablestyle for payments grid

        'If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
        '    DoctorCriteria = " AND tblPayment.PracticeId=" & Val(lkASelectPractice.EditValue)
        'Else
        '    DoctorCriteria = String.Empty
        'End If
    End Sub

    Private Sub FillTaskMessagesGrid()
        Dim dsTemp As DataSet
        Dim strQuery As String = ""
        Try
            Dim DoctorCriteria As String
            If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
                DoctorCriteria = String.Empty
            Else
                DoctorCriteria = " AND (T.ByUser=" & GetPracticeId(gintUserID) & " OR T.ForUser=" & GetPracticeId(gintUserID) & ")"
            End If
            strQuery = "SELECT TaskID [record_id],TaskDesc [Task],CreationDate [Creation Date], " & _
                        "DueDate [Due Date], Case When Completed=0 Then 'No' Else 'Yes' End [Completed],Priority " & _
                        ",U.FullName [By User],U1.FullName [To User] FROM tblTasks T " & _
                        "INNER JOIN vwUserDetails U on T.ByUser=U.UserId " & _
                        "INNER JOIN vwUserDetails U1 on T.ForUser=U1.UserId " & _
                        "LEFT JOIN tblPatientInfo P On T.PatientId=P.PatientId " & _
                        " WHERE T.PatientId=" & PatientId & DoctorCriteria

            dsTemp = FillDataSet(strQuery)
            With grdTask
                .BeginUpdate()
                .DataSource = dsTemp.Tables(0)
                .EndUpdate()
                .ForceInitialize()
            End With
            With gdvTask
                'Primary Key Field
                .Columns("record_id").Visible = False
                .Columns("record_id").OptionsColumn.ShowInCustomizationForm = False
                .Columns("Creation Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("Creation Date").DisplayFormat.FormatString = gstrDtFormat
                .Columns("Due Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("Due Date").DisplayFormat.FormatString = gstrDtFormat
                .Columns("Completed").Width = 50
                .Columns("Priority").Width = 50
            End With
            dsTemp.Dispose()

            dsTemp = FillDataSet("SELECT MessageId,Message,SenderId, U.FullName [Send By],U1.FullName [Send To] " & _
                                ",MessageDate [Date] FROM tblMessages " & _
                                "JOIN vwUserDetails U ON SenderId=U.UserId " & _
                                "JOIN vwUserDetails U1 ON ReceiverId=U1.UserId Where tblMessages.PatientId=" & PatientId)
            gdvMessages.Columns.Clear()
            memoMessages = New RepositoryItemMemoEdit
            memoMessages.Name = "Message"
            With grdMessages
                .BeginUpdate()
                .DataSource = dsTemp.Tables(0)
                .EndUpdate()
                .ForceInitialize()
            End With
            With gdvMessages
                'Primary Key Field
                .Columns("MessageId").Visible = False
                .Columns("MessageId").OptionsColumn.ShowInCustomizationForm = False
                .Columns("SenderId").Visible = False
                .Columns("SenderId").OptionsColumn.ShowInCustomizationForm = False
                .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("Date").DisplayFormat.FormatString = gstrDtFormat & " hh:mm tt"
                .Columns("Message").ColumnEdit = memoMessages
                .ExpandAllGroups()
                .BestFitColumns()
                .OptionsView.RowAutoHeight = True
                gdvMessages.OptionsBehavior.Editable = False
            End With
            dsTemp.Dispose()
        Catch ex As Exception

        End Try
    End Sub


    Private Sub FillPaymentGrid()
        Dim dsTemp As DataSet
        Dim DoctorCriteria As String
        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
            DoctorCriteria = " AND tblVisits.PracticeId=" & GetPracticeId(gintUserID) & " "
        Else
            DoctorCriteria = String.Empty
        End If

        dsTemp = FillDataSet("SELECT  DISTINCT tblPayment.PaymentId, tblPayment.PatientId, tblPayment.PaymentTypeId as TypePaymentId,PaymentType,PaymentDate [Date],CAST(Payment AS DEC(8,2)) AS Payment,InsuranceCompanyId,tblPayment.CheckId as CheckId,Status,Number,BankName,CheckDate,Drawer  FROM (tblPayment JOIN LtblPaymentType ON tblPayment.PaymentTypeId=LtblPaymentType.PaymentTypeId)  JOIN tblVisits ON tblVisits.PatientId=tblPayment.PatientId LEFT OUTER JOIN tblCheck ON tblPayment.CheckId=tblCheck.CheckId  WHERE tblPayment.PatientId = " & PatientId & DoctorCriteria)

        With grdAPayments
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With

        rptxtPayment = New RepositoryItemTextEdit
        rptxtPayment.Mask.MaskType = Mask.MaskType.Numeric
        rptxtPayment.Mask.EditMask = "c2"
        rptxtPayment.Mask.UseMaskAsDisplayFormat = True

        grdAPayments.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rptxtPayment})
        With gdvAPayments
            .Columns("PaymentId").Visible = False
            .Columns("PatientId").Visible = False
            .Columns("TypePaymentId").Visible = False
            .Columns("InsuranceCompanyId").Visible = False
            .Columns("CheckId").Visible = False
            .Columns("Status").Visible = False
            .Columns("Number").Visible = False
            .Columns("BankName").Visible = False
            .Columns("CheckDate").Visible = False
            .Columns("Drawer").Visible = False
            .Columns("Payment").ColumnEdit = rptxtPayment
        End With
        dsTemp.Dispose()
    End Sub

    Private Sub CalCulateChargePayment()
        'fill total Charges text
        Dim i As Integer 'loop variable
        Dim TotalCharge As Double

        'Dim dtCharges As DataTable = dgdCharges.DataSource

        'calculate total charge
        For i = 0 To gdvACharges.RowCount - 1
            If Val(Trim(gdvACharges.GetRowCellValue(i, "ChargeId") & "")) <= 0 Then Continue For
            TotalCharge = TotalCharge + Val(gdvACharges.GetRowCellValue(i, "Total"))
        Next

        'txtTotalCharge.Text = Convert.ToString(TotalCharge)
        txtTotalCharge.Text = TotalCharge.ToString("0.00")
        'txtTotalCharge.Text.Format("0.00")


        'Dim TempString As String = txtTotalCharge.Text

        'fill total Payment Text
        Dim TotalPayment As Double

        'calculate total payment
        For i = 0 To gdvAPayments.RowCount - 1
            If Val(Trim(gdvAPayments.GetRowCellValue(i, "PaymentId") & "")) <= 0 Then Continue For
            TotalPayment = TotalPayment + Val(gdvAPayments.GetRowCellValue(i, "Payment"))
        Next
        txtTotalPayment.Text = TotalPayment.ToString("0.00")
        'txtTotalPayment.Text.Format("0.00")

        'fill total balance text
        Dim TotalBalance As Double
        TotalBalance = TotalCharge - TotalPayment
        txtTotalBalance.Text = TotalBalance.ToString("0.00")
        'txtTotalBalance.Text.Format("0.00")
    End Sub

    Private Sub FillImageTab()
        'Image tab

        'Populate ImageType combo box
        'PopulateList(cmbImageType, "SELECT ImageType,ImageTypeId FROM LtblImageType ORDER BY ImageType", "ImageType", "ImageTypeId")
        Call PopulateLookupDX(lkIImageType, "ImageType", "ImageTypeId", "LtblImageType", "ImageTypeId,ImageType", , "ImageType")

        'create image tablestyle
        Dim btnOpen As New Button
        With btnOpen
            .Text = "Open"
            .BackColor = Color.Silver
            .Size = New Size(60, 22)
            .Cursor = Cursors.Arrow
            .FlatStyle = FlatStyle.System
            .Focus()
        End With

        AddHandler btnOpen.Click, AddressOf btnOpen_Click
        FillImageGrid()

    End Sub

    Private Sub FillImageGrid()
        Dim strQuery As String
        strQuery = "SELECT ImageId, PatientId,ImageName [Name], ImagePath, Description, Comments, tblPatientsImages.ImageTypeId,ImageType,' Open' as OpenButton FROM tblPatientsImages JOIN LtblImageType ON tblPatientsImages.ImageTypeId=LtblImageType.ImageTypeId  WHERE PatientID = " & PatientId
        Dim dsTemp As DataSet
        dsTemp = FillDataSet(strQuery)
        With grdIRecords
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
        With gdvIRecords
            .Columns("PatientId").Visible = False
            .Columns("ImageId").Visible = False
            .Columns("ImagePath").Visible = False
            .Columns("Description").Visible = False
            .Columns("Comments").Visible = False
            .Columns("ImageTypeId").Visible = False
        End With
    End Sub

    Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
        ShowImage()
    End Sub

    Private Sub ShowImage()
        'If picPreview.Image Is Nothing Then
        '    Exit Sub
        'End If

        Try
            System.Diagnostics.Process.Start(gdvIRecords.GetRowCellValue(gdvIRecords.FocusedRowHandle, "ImagePath"))

        Catch ex As Exception
            MessageBox.Show("File not found.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Public Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        If btnAdd.Text = "&New Patient" Then
            PatientId = -1      'must set to -1. Other tabs will be inaccessible now till patient is added
            Me.Text = "Patient Information"

            Call Clearfields(grbDemographics)
            Call Clearfields(grbHealthInsurance)
            Call Clearfields(grbKin)
            btnAdd.Text = "&Add"

            btnDelete.Enabled = False   'disable other buttons
            btnUpdate.Enabled = False
            btnDRegister.Enabled = False

            xtpAccount.Enabled = False                  'hide other tabs
            xtpImage.Enabled = False
            xtpPastVisits.Enabled = False
            xtpVaccinationRecord.Enabled = False
            mblnChanged = False
            'txtDFirstName.Focus()
            cboTitle.Focus()
            mstrMode = "Add"
        Else                             'User has clicked button with Add text 
            If IsValidEntry() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If

            If blnSaveRecords(0) = False Then
                Exit Sub
            End If
            mstrMode = ""
            btnAdd.Text = "&New Patient"
            btnDelete.Enabled = True
            btnUpdate.Enabled = True
            btnDRegister.Enabled = True
            If mblnFromOutside = True Then
                PtId = PatientId
                Me.Close()
            End If
        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        If IsValidEntry() = False Then
            Exit Sub
        End If
        mstrMode = "Edit"
        If blnSaveRecords(0) = False Then
            Exit Sub
        End If
        'Cursor.Current = Cursors.WaitCursor

        'Dim Ssql As String

        ''*************************************************************************************
        'Ssql = "UPDATE tblPatientInfo  SET FirstName='" & txtFirstName.Text & "',LastName='" & txtLastName.Text & "',SexId='" & cmbGender.SelectedValue & "',MaritalStatusId='" & cmbMaritalStatus.SelectedValue & "',Address1='" & txtAddress1.Text & "',Address2='" & txtAddress2.Text & "',TownId='" & cmbTown.SelectedValue & "',ParishId='" & cmbParish.SelectedValue & "',InsuranceCompanyId=" & IIf(cmbInsuranceCompany.SelectedIndex = 0, "NULL", cmbInsuranceCompany.SelectedValue) & ",InsuranceNumber='" & txtInsuranceNumber.Text & "',InsuranceName='" & txtInsuredName.Text & "',Occupation='" & txtOccupation.Text & "',WorkPhone='" & txtWorkPhone.Text & "',HomePhone='" & txtHomePhone.Text & "', NextOfKinName='" & txtKinName.Text & " ',NextOfKinPhone='" & txtKinPhone.Text & " ',NextOfKinOccupation='" & txtKinOccupation.Text & "',DateOfBirth=" & IIf(dtpBirthDate.Checked, "'" & dtpBirthDate.Value & "'", "NULL") & ",CountryId='" & cmbCountry.SelectedValue & "' WHERE PatientID=" & PatientId & " "
        ''*********************************************************************************************************




        'Dim cn As New SqlConnection(CnStr)
        'Dim dr As SqlDataReader

        'Try
        '    Dim dc As New SqlCommand(Ssql, cn)
        '    cn.Open()
        '    dc.ExecuteNonQuery()
        '    MessageBox.Show("Patient information updated.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        'Catch exp As SqlException
        '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        'Catch ex As Exception
        '    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        'Finally
        '    cn.Close()
        '    Cursor.Current = Cursors.Default
        'End Try
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim blnTrnasaction As Boolean

        Try

            If MessageBox.Show("Are you sure you want to delete this record", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True
                Call UpdateTable("tblPatientInfo", "Void=1", "PatientId=" & PatientId)
                gtrnWebPlusMed.Commit()
                blnTrnasaction = False
                MessageBox.Show("Record deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Call Clearfields(grbDemographics)
            End If
            mblnChanged = False

        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub dtDDOB_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtDDOB.EditValueChanged
        mblnChanged = True
        If Not IsDBNullOrNothing(dtDDOB.EditValue) Then
            If DateDiff(DateInterval.Year, dtDDOB.EditValue, Today) <> 0 Then 'if patient is of months
                lblAgeInformation.Text = "Patient is " & DateDiff(DateInterval.Year, dtDDOB.EditValue, Today) & " Years."
            Else
                lblAgeInformation.Text = "Patient is " & DateDiff(DateInterval.Month, dtDDOB.EditValue, Today) & " Months."
            End If
        Else
            lblAgeInformation.Text = String.Empty
        End If
    End Sub


    Private Function CheckIfRegisteredForToday(ByVal PatientId As Integer) As Boolean
        Try
            Dim Registered As Boolean
            Dim dsTemp As DataSet = FillDataSet("SELECT COUNT(PatientId) as [PatientNo] FROM tblVisits WHERE PatientId =" & PatientId & " AND VisitDate BETWEEN '" & Today.ToShortDateString & " 00:00' AND '" & Today.ToShortDateString & " 23:59'")
            If dsTemp.Tables(0).Rows.Count > 0 Then
                If Val(dsTemp.Tables(0).Rows(0).Item("PatientNo")) > 0 Then
                    Registered = True
                End If
            End If
            Return Registered
        Catch ex As Exception

        End Try
    End Function

    Private Sub btnRegister_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDRegister.Click
        'find out if patient is registered for Today
        If CheckIfRegisteredForToday(PatientId) = True Then
            MessageBox.Show("This patient is already registered for today.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If

        Dim RegisterPatientForm As New frmRegistration(-1, PatientId)
        RegisterPatientForm.ShowDialog()
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub


    Private Function IsPaymentBoxValid() As Boolean

        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsPaymentBoxValid = False

        'If IsDBNullOrNothing(lkDMaritalStatus.EditValue) Then
        '      strMsg = "Please select Marital Status."
        '      lkDMaritalStatus.Focus()
        '  End If


        If IsDBNullOrNothing(dtPaymentDate.EditValue) Then
            strMsg = "Please select Payment Date"
            dtPaymentDate.Focus()
        ElseIf IsDBNullOrNothing(lkAPaymentType.EditValue) Then
            strMsg = "Please select Payment Type."
            lkAPaymentType.Focus()

        ElseIf Trim(txtAPayment.Text) = "" Then
            strMsg = "Please enter Payment."
            txtAPayment.Focus()
        ElseIf Val(lkAPaymentType.EditValue) = 4 OrElse Val(lkAPaymentType.EditValue) = 8 Then
            If Trim(txtAChqCrdtDrawer.Text) = "" Then
                strMsg = "Please enter " & IIf(Val(lkAPaymentType.EditValue) = 4, "Drawer's", "Card holder's") & " Name."
                txtAChqCrdtDrawer.Focus()
            End If
        End If

        If Trim(strMsg) <> "" Then
            IsPaymentBoxValid = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsPaymentBoxValid = True
        End If

    End Function

    Private Sub lkAPaymentType_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkAPaymentType.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkAPaymentType, "PaymentType", "PaymentTypeId", "LtblPaymentType", "PaymentTypeId,PaymentType", , "PaymentType")
        End If
    End Sub


    Private Sub lkAPaymentType_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkAPaymentType.EditValueChanged
        mblnAChanged = True
        If IsDBNullOrNothing(lkAPaymentType.EditValue) Then
            Exit Sub
        End If

        'neither credit nor cheque payment selected
        If Val(lkAPaymentType.EditValue) <> 4 AndAlso Val(lkAPaymentType.EditValue) <> 8 Then
            grbChequeCredit.Enabled = False
            txtAChqCrdtNo.Text = Nothing

            lkAInsuranceCompany.EditValue = Nothing
            lkAInsuranceCompany.Visible = IIf(Val(lkAPaymentType.EditValue) = 5, True, False) 'dont show this field except for Insurance copayment
            lblAInsuranceCompany.Visible = IIf(Val(lkAPaymentType.EditValue) = 5, True, False) 'dont show this field except for Insurance copayment
            dtAChqCrdtDate.EditValue = Nothing
            txtAChqCrdtBank.Text = Nothing
        End If

        'cheque payment is selected
        If Val(lkAPaymentType.EditValue) = 4 Then
            grbChequeCredit.Enabled = True
            'grbChequeCredit.Visible = True
            grbChequeCredit.Text = "For Check Payment"
            lblAChqCreditNo.Text = "Check Number:"
            lblAChqCreditDate.Text = "Check Date:"
            lkAInsuranceCompany.EditValue = Nothing
            lblAChqCreditBankName.Text = "Bank Name:"
            lblAChqCreditDrawer.Text = "Drawer:"
        End If

        'card payment is selected
        If Val(lkAPaymentType.EditValue) = 8 Then
            grbChequeCredit.Enabled = True
            'grbChequeCredit.Visible = True
            grbChequeCredit.Text = "For Credit Card"
            lblAChqCreditNo.Text = "Card Number"
            lblAChqCreditDate.Text = "Expiry Date"
            lkAInsuranceCompany.EditValue = Nothing
            lblAChqCreditBankName.Text = "Bank Name"
            lblAChqCreditDrawer.Text = "Card Holder's Name"
        End If
    End Sub

    'this function inserts check data and sets CheckId to newly inserted CheckId.Returns true if successful
    Private Sub InsertUpdateCheckData(ByRef CheckId As Integer, ByVal IsInsertQuery As Boolean)
        Dim strQuery As String

        Try
            If IsInsertQuery Then
                'Insert data for check or credit card.
                'Ssql = "INSERT INTO tblCheck (" & IIf(ServerType = "sub", "PaymentId,", String.Empty) & " Status, Number, BankName, CheckDate, Amount,Drawer) VALUES ("
                'Ssql = Ssql & IIf(ServerType = "sub", GetNextId("tblCheck", "CheckId").ToString & ", ", String.Empty)
                'Ssql = Ssql & IIf(cmbPaymentType.SelectedValue = 4, 1, "NULL") & ","
                'Ssql = Ssql & "'" & txtNumber.Text & "',"
                'Ssql = Ssql & "'" & txtBankName.Text & "',"
                'Ssql = Ssql & "'" & dtpChequeDate.Value.ToShortDateString & "',"
                'Ssql = Ssql & txtPayment.Text & ","
                'Ssql = Ssql & "'" & txtdrawer.Text & "'"
                'Ssql = Ssql & ")"
                strQuery = IIf(lkAPaymentType.EditValue = 4, 1, "NULL") & _
                        "," & Trim(SmartReplace(txtAChqCrdtNo.Text) & "") & _
                        "," & Trim(SmartReplace(txtAChqCrdtBank.Text) & "") & _
                        ",'" & Format(CDate(dtAChqCrdtDate.EditValue), gstrDtFormat) & "'" & _
                        "," & Val(txtAPayment.Text) & _
                        "," & Trim(SmartReplace(txtAChqCrdtDrawer.Text) & "")
                Call InsertintoTable("tblCheck", strQuery)
            Else
                'Update Check data
                'Ssql = "UPDATE tblCheck SET "
                'Ssql = Ssql & " Status=" & IIf(cmbPaymentType.SelectedValue = 4, 1, "NULL") & ","
                'Ssql = Ssql & " Number=" & "'" & txtNumber.Text & "',"
                'Ssql = Ssql & " BankName=" & "'" & txtBankName.Text & "',"
                'Ssql = Ssql & " CheckDate=" & "'" & dtpChequeDate.Value.ToShortDateString & "',"
                'Ssql = Ssql & " Amount=" & txtPayment.Text & ","
                'Ssql = Ssql & " Drawer=" & "'" & txtdrawer.Text & "'"
                'Ssql = Ssql & " WHERE CheckId=" & CheckId
                strQuery = " Status=" & IIf(lkAPaymentType.EditValue = 4, 1, "NULL") & _
                        ",Number=" & Trim(SmartReplace(txtAChqCrdtNo.Text) & "") & _
                        ",BankName=" & Trim(SmartReplace(txtAChqCrdtBank.Text) & "") & _
                        ",CheckDate='" & Format(CDate(dtAChqCrdtDate.EditValue), gstrDtFormat) & "'" & _
                        ",Amount=" & Val(txtAPayment.Text) & _
                        ",Drawer=" & Trim(SmartReplace(txtAChqCrdtDrawer.Text) & "")
                Call UpdateTable("tblCheck", strQuery, "CheckId=" & CheckId)
            End If


        Catch ex As Exception
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnAccountNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccountNew.Click
        If btnAccountNew.Text = "&New" Then     'check if user has clicked New button
            txtAPayment.Text = Nothing  '  if so set textboxes to empty string 
            lkAPaymentType.EditValue = Nothing  '  and change button text to Add 
            lkAInsuranceCompany.EditValue = Nothing
            btnAccountUpdate.Enabled = False
            btnAccountDelete.Enabled = False
            btnAccountNew.Text = "&Add"
            mblnAChanged = False
            mstrAMode = "Add"
            lkAPaymentType.Focus()
            dtPaymentDate.EditValue = Format(Today, gstrDtFormat)
            dtPaymentDate.Enabled = False
        Else                                'User has clicked button with Add text 
            If IsPaymentBoxValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If

            If blnSaveRecords(3) = False Then
                Exit Sub
            End If
            mstrAMode = ""
            Call FillPaymentGrid()
            Call CalCulateChargePayment()
            grbPayments.Enabled = False
            grbButtons.Enabled = False
            btnEnterPayment.Enabled = True
            'Dim cn As New SqlConnection(CnStr)
            'Cursor.Current = Cursors.WaitCursor

            'Try
            '    Dim CheckId As Integer

            '    If cmbPaymentType.SelectedValue = 4 OrElse cmbPaymentType.SelectedValue = 8 Then
            '        InsertUpdateCheckData(CheckId, True)
            '    End If

            '    Dim Ssql As String
            '    Dim dcInsert As New SqlCommand

            '    cn.Open()
            '    Ssql = "INSERT INTO tblPayment(" & IIf(ServerType = "sub", "PaymentId,", String.Empty) & " PatientId,PracticeId,PaymentTypeId,PaymentDate,Payment,InsuranceCompanyId,CheckId) VALUES ("
            '    Ssql = Ssql & IIf(ServerType = "sub", GetNextId("tblPayment", "PaymentId").ToString & ", ", String.Empty)
            '    Ssql = Ssql & PatientId & ","
            '    Ssql = Ssql & cmbSelectPractice.SelectedValue & ","
            '    Ssql = Ssql & cmbPaymentType.SelectedValue & ","
            '    Ssql = Ssql & "'" & Today.ToShortDateString & "',"
            '    Ssql = Ssql & " CAST(" & Val(txtPayment.Text) & " AS Dec(8,2))" & ","
            '    Ssql = Ssql & IIf(cmbAccInsuranceCompany.SelectedIndex = 0, "NULL", cmbAccInsuranceCompany.SelectedValue) & ","
            '    Ssql = Ssql & CheckId & ")"

            '    dcInsert.CommandText = Ssql
            '    dcInsert.Connection = cn
            '    dcInsert.ExecuteNonQuery()
            '    PopulateAccountPaymentGrid()
            '    CalCulateChargePayment()
            'Catch ex As SqlException
            '    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Catch exc As Exception
            '    MessageBox.Show(exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Finally
            '    cn.Close()
            '    btnNewPayments.Text = "&New"
            '    btnUpdatePayment.Enabled = True
            '    btnDeletePayment.Enabled = True
            '    Cursor.Current = Cursors.Default
            'End Try
        End If
    End Sub

    Private Sub btnAccountUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccountUpdate.Click
        Try
            If gdvAPayments.RowCount <= 0 Then Exit Sub
            If IsPaymentBoxValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If
            mstrAMode = "Edit"
            If blnSaveRecords(3) = False Then
                Exit Sub
            End If
            Call FillPaymentGrid()
            Call CalCulateChargePayment()
            grbPayments.Enabled = False
            grbButtons.Enabled = False
            btnEnterPayment.Enabled = True
        Catch ex As Exception

        End Try
        'If dgdPayments.VisibleRowCount = 0 Then
        '    Exit Sub
        'End If

        'If IsPaymentBoxValid() = False Then
        '    Exit Sub
        'End If

        'Cursor.Current = Cursors.WaitCursor

        'Dim Ssql As String

        'Dim cn As New SqlConnection(CnStr)
        'Dim dr As SqlDataReader

        'Try
        '    Dim dt As DataTable = dgdPayments.DataSource
        '    Dim RowSelected As Integer = dgdPayments.CurrentRowIndex

        '    If cmbPaymentType.SelectedValue = 4 OrElse cmbPaymentType.SelectedValue = 8 Then
        '        InsertUpdateCheckData(dt.Rows(RowSelected).Item("CheckId"), False)
        '    End If

        '    '*********************************************************************************************************
        '    Ssql = "UPDATE tblPayment  SET "
        '    Ssql = Ssql & " PatientId = " & dt.Rows(RowSelected).Item("PatientId") & ", "
        '    Ssql = Ssql & " PracticeId = " & cmbSelectPractice.SelectedValue & ","
        '    Ssql = Ssql & " PaymentTypeId= " & cmbPaymentType.SelectedValue & ","
        '    Ssql = Ssql & " PaymentDate='" & Today.ToShortDateString & "',"
        '    Ssql = Ssql & " Payment= " & Val(txtPayment.Text) & ","
        '    Ssql = Ssql & " InsuranceCompanyId= " & IIf(cmbInsuranceCompany.SelectedIndex = 0, "NULL", cmbInsuranceCompany.SelectedValue)
        '    Ssql = Ssql & " WHERE PaymentId=" & dgdPayments.Item(dgdPayments.CurrentRowIndex, 0)
        '    '*********************************************************************************************************

        '    Dim dc As New SqlCommand(Ssql, cn)
        '    cn.Open()
        '    dc.ExecuteNonQuery()
        '    MessageBox.Show("Payment updated", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    PopulateAccountPaymentGrid()
        '    CalCulateChargePayment()

        'Catch exp As SqlException
        '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        'Catch ex As Exception
        '    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        'Finally
        '    cn.Close()
        '    Cursor.Current = Cursors.Default

        'End Try
    End Sub

    Private Sub btnAccountDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccountDelete.Click
        Dim blnTrnasaction As Boolean
        If gdvAPayments.RowCount <= 0 Then Exit Sub
        Try

            If MessageBox.Show("Are you sure you want to permanently delete this record", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True
                Call DeleteFromTable("tblPayment", "PaymentId=" & PaymentId)
                gtrnWebPlusMed.Commit()
                blnTrnasaction = False
                MessageBox.Show("Record deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                FillPaymentGrid()
                CalCulateChargePayment()
                grbPayments.Enabled = False
                grbButtons.Enabled = False
                btnEnterPayment.Enabled = True
            End If
            mblnAChanged = False

        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvAPayments_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvAPayments.Click
        'If dgdPayments.VisibleRowCount = 0 Then
        '    Exit Sub
        'End If

        'Dim dt As DataTable = dgdPayments.DataSource
        'Dim RowNumber As Integer = dgdPayments.CurrentRowIndex

        'If RowNumber + 1 > dt.Rows.Count Then
        '    Exit Sub
        'End If

        'cmbPaymentType.SelectedValue = dt.Rows(RowNumber).Item("TypePaymentId")
        'txtPayment.Text = dt.Rows(RowNumber).Item("Payment") & ""

        ''if insurance comapny field is Null then set index of combobox to -1
        'If IsDBNull(dt.Rows(RowNumber).Item("InsuranceCompanyId")) Then
        '    cmbAccInsuranceCompany.SelectedIndex = 0
        'Else
        '    cmbAccInsuranceCompany.SelectedValue = dt.Rows(RowNumber).Item("InsuranceCompanyId")
        'End If

        'txtBankName.Text = dt.Rows(RowNumber).Item("BankName") & ""
        'txtNumber.Text = dt.Rows(RowNumber).Item("Number") & ""
        'txtdrawer.Text = dt.Rows(RowNumber).Item("Drawer") & ""
    End Sub

    Private Sub btnAccountClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccountClose.Click
        Me.Close()
    End Sub

    Private Sub btnVaccinationClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVaccinationClose.Click
        Me.Close()
    End Sub

    Private Sub btnPastVisitNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPastVisitNew.Click
        If btnPastVisitNew.Text = "&New" Then
            dtPVisitDate.EditValue = Format(Today, gstrDtFormat) & " " & Format(Today, "hh:mm tt")
            lkPVisitLocation.EditValue = Nothing
            txtPComplaint.Text = Nothing
            txtPTherapy.Text = Nothing
            'PopulateDiagnosisGrid(-1) 'grid will not get populated because -1 VisitId is not there but we will get dataSource format.
            btnPastVisitNew.Text = "&Add"
            btnPastVisitUpdate.Enabled = False
            'gdvPRecords.Enabled = False
            mstrPMode = "Add"
            Call InitialiseDataEntry()
            mblnPchanged = False
            dtPVisitDate.Focus()
        Else
            If Not IsValidVisitTab() Then
                Exit Sub
            End If

            If blnSaveRecords(1) = False Then
                Exit Sub
            End If
            mstrPMode = ""
            Call PastVisitGridLoad()
            btnPastVisitNew.Text = "&New"
            btnPastVisitUpdate.Enabled = True
            'Cursor.Current = Cursors.WaitCursor
            'Dim Ssql As String

            ''*********************************************************************************** 
            'Ssql = "INSERT INTO tblVisits(PatientId, VisitDate, VisitLocationId, AppointmentTypeId, PresentingComplaint, PresentingComplaintHistory, DaysToNextAppointment, Therapy,PatientStatusId, PracticeId) VALUES("
            'Ssql = Ssql & PatientId & ","
            'Ssql = Ssql & "'" & dtPVisitDate.Value & "'" & ","
            'Ssql = Ssql & cmbVisitLocation.SelectedValue & ","
            'Ssql = Ssql & "1" & ","
            'Ssql = Ssql & "'" & txtPresentingComplaint.Text & "'" & ","
            'Ssql = Ssql & "'" & String.Empty & "'" & ","
            'Ssql = Ssql & "0" & ","
            'Ssql = Ssql & "'" & txtTherapy.Text & "'" & ","
            'Ssql = Ssql & PatientStatus.Paid & ","
            'Ssql = Ssql & GetPracticeId(UserId).ToString
            'Ssql = Ssql & ")"
            ''************************************************************************************
            'Dim cn As New SqlConnection(CnStr)
            'Try
            '    'insert in table tblVisits.
            '    Dim dc As New SqlCommand(Ssql, cn)
            '    cn.Open()
            '    dc.ExecuteNonQuery()

            '    'get Visit id
            '    Ssql = "SELECT MAX(VisitId) from tblVisits"
            '    Dim dcScalar As New SqlCommand(Ssql, cn)
            '    dcScalar.CommandText = Ssql
            '    VisitId = dcScalar.ExecuteScalar()

            '    'insert in table tblVisitResult.
            '    dc.CommandType = CommandType.Text
            '    dc.CommandText = "INSERT INTO tblVisitResult (Therapy, Hospitalised, VisitId)  VALUES(" & "'" & txtTherapy.Text & "'" & ",1," & VisitId & ")"
            '    dc.ExecuteNonQuery()

            '    'insert diagnosis.
            '    InsertFromDiagnosisGrid(VisitId)
            '    PopulateVisitGrid()
            'Catch exp As SqlException
            '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Catch exp As Exception
            '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Finally
            '    cn.Close()
            '    btnPastVisitNew.Text = "&New"
            '    btnPastVisitUpdate.Enabled = True
            '    dgdVisits.Enabled = True
            '    Cursor.Current = Cursors.Default
            'End Try

        End If
    End Sub

    Private Function IsValidVisitTab() As Boolean
        'check if office location is selected

        Dim strMsg As String = ""
        IsValidVisitTab = False

        If IsDBNullOrNothing(lkPVisitLocation.EditValue) Then
            strMsg = "Please select Visit Location."
            lkPVisitLocation.Focus()
        End If


        If Trim(strMsg) <> "" Then
            IsValidVisitTab = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidVisitTab = True
        End If

    End Function

    Private Sub btnPastVisitUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPastVisitUpdate.Click
        If Not IsValidVisitTab() Then
            Exit Sub
        End If
        mstrPMode = "Edit"
        If blnSaveRecords(1) = False Then
            Exit Sub
        End If
        Call PastVisitGridLoad()

        ''check if there is patient to update
        'Dim dt As DataTable = dgdVisits.DataSource
        'If dt.Rows.Count = 0 Then
        '    Exit Sub
        'End If

        'Cursor.Current = Cursors.WaitCursor

        'Dim Ssql As String

        ''*************************************************************************************
        'Ssql = "UPDATE tblVisits  SET "
        'Ssql = Ssql & "VisitDate =" & "'" & dtPVisitDate.Value & "'" & ","
        'Ssql = Ssql & "VisitLocationId =" & cmbVisitLocation.SelectedValue & ","
        'Ssql = Ssql & "PresentingComplaint =" & "'" & txtPresentingComplaint.Text & "'"
        'Ssql = Ssql & " WHERE VisitId=" & VisitId
        ''***************************************************************************
        'Dim cn As New SqlConnection(CnStr)
        'Dim dr As SqlDataReader

        'Try
        '    Dim dc As New SqlCommand(Ssql, cn)
        '    cn.Open()
        '    dc.ExecuteNonQuery()

        '    dc.CommandType = CommandType.Text
        '    dc.CommandText = "UPDATE  tblVisitResult SET  Therapy ='" & txtTherapy.Text & "'"
        '    dc.ExecuteNonQuery()

        '    'code to update Diagnosis.
        '    'we are not updating diagnosis rather we are inserting them or deleting them.
        '    InsertFromDiagnosisGrid(VisitId)

        '    Dim RowNumber As Integer = dgdVisits.CurrentRowIndex
        '    PopulateVisitGrid()
        '    dgdVisits.Select(RowNumber)
        '    dgdVisits_Click(dgdVisits, e)

        '    MessageBox.Show("Visit updated.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        'Catch exp As SqlException
        '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        'Catch ex As Exception
        '    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        'Finally
        '    cn.Close()
        '    Cursor.Current = Cursors.Default
        'End Try
    End Sub

    Private Sub btnPastVisitClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPastVisitClose.Click
        Me.Close()
    End Sub

    Private Sub gdvPRecords_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvPRecords.DoubleClick

        If gdvPRecords.RowCount <= 0 Then Exit Sub
        If Array.IndexOf(gstrAPForms, "frmDoctorsNote", 0) >= 0 Then
            VisitId = Val(gdvPRecords.GetRowCellValue(gdvPRecords.FocusedRowHandle, "VisitId"))

            Dim DoctorNotesForm As New frmDoctorsNote

            DoctorNotesForm.VisitId = VisitId
            DoctorNotesForm.mstrFrmName = "PatientInfo"
            'DoctorNotesForm.MdiParent = Me.ParentForm
            DoctorNotesForm.ShowInTaskbar = False
            DoctorNotesForm.ShowDialog()
            DoctorNotesForm.Dispose()
            GC.Collect()
            If blnOpnCharge = True Then
                If isLoaded("frmChargeAndPayment") Then Exit Sub
                Dim ChargeAndPaymentForm As New frmChargeAndPayment(VisitId, PatientId, GetPracticeId(gintUserID))
                ChargeAndPaymentForm.Text = Me.Text
                ChargeAndPaymentForm.mblnFrmOutside = False
                ChargeAndPaymentForm.ShowInTaskbar = False
                ChargeAndPaymentForm.ShowDialog()
                ChargeAndPaymentForm.Dispose()
                GC.Collect()
                blnOpnCharge = False
            End If
            
        End If
        Call PastVisitGridLoad()

        'Cursor.Current = Cursors.Default
    End Sub
    Private Function isLoaded(ByVal strFormName As String, Optional ByVal strTag As String = "") As Boolean
        isLoaded = False
        For Each frmchild As Form In Me.ParentForm.MdiChildren
            If Not (frmchild.Tag Is Nothing) Then
                If frmchild.Name.ToString = strFormName And frmchild.Tag.ToString = strTag Then
                    isLoaded = True : frmchild.BringToFront() : Exit Function
                End If
            ElseIf frmchild.Tag Is Nothing Or frmchild.Tag = String.Empty Then
                If frmchild.Name.ToString = strFormName And strTag = String.Empty Then
                    isLoaded = True : frmchild.BringToFront() : Exit Function
                End If
            End If
        Next
    End Function


    Private Sub btnImagePath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImagePath.Click
        Dim dlgFile As New OpenFileDialog

        dlgFile.Filter = "Image File(*.JPG)|*.JPG|Image File(*.BMP)|*.BMP|Image File (*.GIF)|*.GIF|All files (*.*)|*.*"


        If dlgFile.ShowDialog = DialogResult.Cancel Then
            Exit Sub
        Else
            txtIFullPath.Text = dlgFile.FileName
        End If
    End Sub

    Private Sub btnImageNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImageNew.Click
        If btnImageNew.Text = "&New" Then       'check if user has clicked New button
            txtIName.Text = ""              '  if so set textboxes to empty string 
            txtIFullPath.Text = ""          '  and change button text to Add 
            txtIComments.Text = ""
            txtIDescription.Text = ""
            lkIImageType.EditValue = Nothing
            btnImageNew.Text = "&Add"
            mstrIMode = "Add"
            btnImageDelete.Enabled = False
            btnImageUpdate.Enabled = False
            mblnIChanged = False
            txtIName.Focus()
        Else                                     'User has clicked button with Add text 
            If IsImageTabValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If

            If blnSaveRecords(2) = False Then
                Exit Sub
            End If
            mstrIMode = ""
            Call FillImageGrid()
            btnImageNew.Text = "&New"
            btnImageDelete.Enabled = True
            btnImageUpdate.Enabled = True
            'Dim Ssql As String


            ''****************************************************************************************************
            'Ssql = "Insert Into tblPatientsImages(" & IIf(ServerType = "sub", "ImageId,", String.Empty) & "  PatientId,ImageName,ImagePath,Description,Comments,ImageTypeId) values (" & IIf(ServerType = "sub", GetNextId("tblPatientsImages", "ImageId").ToString & ", ", String.Empty) & PatientId & ",'" & txtImageName.Text & "','" & txtImageFilePath.Text & "','" & txtImageDescription.Text & "','" & txtImageComments.Text & "'," & cmbImageType.SelectedValue & ")"
            ''*****************************************************************************************************



            'Dim cn As New SqlConnection(CnStr)
            'Dim dr As SqlDataAdapter

            'Try
            '    Dim dc As New SqlCommand(Ssql, cn)
            '    cn.Open()
            '    dc.ExecuteNonQuery()
            'Catch exp As Exception
            '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Finally
            '    cn.Close()
            '    btnImageNew.Text = "&New"
            '    btnImageDelete.Enabled = True
            '    btnImageUpdate.Enabled = True
            '    PopulateImageGrid()
            'End Try
        End If

    End Sub

    Private Function IsImageTabValid() As Boolean
        Dim strMsg As String = ""
        IsImageTabValid = False

        'If IsDBNullOrNothing(lkPVisitLocation.EditValue) Then
        '    strMsg = "Please select Visit Location."
        '    lkPVisitLocation.Focus()
        'End If

        If Trim(txtIName.Text) = "" Then
            strMsg = "Please enter Image Name."
            txtIName.Focus()
        ElseIf IsDBNullOrNothing(lkIImageType.EditValue) Then
            strMsg = "Please select Image Type."
            lkIImageType.Focus()
        ElseIf Trim(txtIFullPath.Text) = "" Then
            strMsg = "Please select Image Path."
            txtIFullPath.Focus()
        End If

        If Trim(strMsg) <> "" Then
            IsImageTabValid = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsImageTabValid = True
        End If
    End Function

    Private Sub btnImageUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImageUpdate.Click
        If IsImageTabValid() = False Then     'check if user has entered values in textbox
            Exit Sub
        End If
        mstrIMode = "Edit"
        If blnSaveRecords(2) = False Then
            Exit Sub
        End If
        Call FillImageGrid()
        'If dgdImage.VisibleRowCount = 0 Then
        '    MessageBox.Show("There is no image to update", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    Exit Sub
        'End If


        'Dim Ssql As String

        ''***************************************Query Incomplete ***************************************
        'Ssql = "UPDATE tblPatientsImages SET ImagePath='" & txtImageFilePath.Text & "',ImageName='" & txtImageName.Text & "', ImageTypeId='" & cmbImageType.SelectedValue & " ',Description= '" & txtImageDescription.Text & "',Comments='" & txtImageComments.Text & "' WHERE  ImageId=" & dgdImage.Item(dgdImage.CurrentRowIndex, 0)
        ''*****************************************************************************************************



        'Dim cn As New SqlConnection(CnStr)
        'Dim dr As SqlDataReader

        'Try
        '    Dim dc As New SqlCommand(Ssql, cn)
        '    cn.Open()
        '    dc.ExecuteNonQuery()
        '    MessageBox.Show("Image updated", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        'Catch exp As Exception
        '    MessageBox.Show(exp.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        'Finally
        '    cn.Close()
        '    PopulateImageGrid()
        'End Try

    End Sub

    Private Sub btnImageDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImageDelete.Click

        Dim blnTrnasaction As Boolean
        If gdvIRecords.RowCount <= 0 Then Exit Sub
        Try

            If MessageBox.Show("Are you sure you want to permanently delete this record", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True
                Call DeleteFromTable("tblPatientsImages", "ImageId=" & ImageId)
                gtrnWebPlusMed.Commit()
                blnTrnasaction = False
                MessageBox.Show("Record deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                FillImageGrid()
                gdvIRecords.Focus()
            End If

            mblnIChanged = False
        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub btnImageClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImageClose.Click
        Me.Close()
    End Sub

    Private Sub pcbImage_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pcbImage.DoubleClick
        ShowImage()
    End Sub

    Private Sub btnVaccinationSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVaccinationSave.Click
        If gdvVaccinationHistory.RowCount <= 0 Then Exit Sub
        If blnSaveRecords(4) = False Then
            Exit Sub
        End If
        mstrVMode = ""
        Call FillVaccinationHistoryGrid()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call Clearfields(grbDemographics)
        Call Clearfields(grbHealthInsurance)
        Call Clearfields(grbKin)
        Call FillDemographicsPage(Pid)
        If Pid > 0 Then

            btnAdd.Text = "&New Patient"
            btnDelete.Enabled = True
            btnDRegister.Enabled = True
        End If
        mblnChanged = False

    End Sub

    Private Sub lkDTown_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDTown.ButtonClick
        If e.Button.Index = 1 Then    'Refresh data
            'Populate Town combo box 
            Call PopulateLookupDX(lkDTown, "Town", "TownId", "LtblTown", "TownId,Town", , "Town")
        End If
    End Sub

    Private Sub lkDTown_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkDTown.EditValueChanged
        mblnChanged = True
        If Not IsDBNullOrNothing(lkDTown.EditValue) Then
            lkDParish.EditValue = CInt(Val(strRecordID("LtblTown", "ParishId", "TownId=" & Val(lkDTown.EditValue))))
        End If
    End Sub

    Private Sub lkDParish_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDParish.ButtonClick
        If e.Button.Index = 1 Then    'Refresh Data
            'Populate Parish combo box
            Call PopulateLookupDX(lkDParish, "Parish", "ParishId", "LtblParish", "ParishId,Parish", , "Parish")
        End If
    End Sub

    Private Sub lkDParish_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkDParish.EditValueChanged
        mblnChanged = True
        If Not IsDBNullOrNothing(lkDParish.EditValue) Then
            lkDCountry.EditValue = CInt(Val(strRecordID("LtblParish", "CountryId", "ParishId=" & Val(lkDParish.EditValue))))
        End If
    End Sub

    Private Sub lkDTown_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkDTown.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkDTown.EditValue = Nothing
            lkDTown.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblTown"
            .mintGrbId = 2
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkDTown, "Town", "TownId", "LtblTown", "TownId,Town", , "Town")
            If mlngLookUpId > 0 Then
                lkDTown.EditValue = CInt(mlngLookUpId)
            Else
                lkDTown.EditValue = Nothing
                lkDTown.Focus()
            End If

            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkDCountry_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDCountry.ButtonClick
        If e.Button.Index = 1 Then          'Refresh Data
            'Populate Country combo box
            Call PopulateLookupDX(lkDCountry, "Country", "CountryId", "LtblCountry", "CountryId,Country", , "Country")
        End If
    End Sub

    Private Sub lkDGender_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDGender.ButtonClick
        If e.Button.Index = 1 Then          'Refresh Data
            'Populate Gender combo box
            Call PopulateLookupDX(lkDGender, "Sex", "SexId", "LtblSex", "SexId,Sex", , "Sex")
        End If
    End Sub

    Private Sub lkDMaritalStatus_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDMaritalStatus.ButtonClick
        If e.Button.Index = 1 Then  'Refresh Data
            'Populate MaritalStatus combo box
            Call PopulateLookupDX(lkDMaritalStatus, "MaritalStatus", "MaritalStatusId", "LtblMaritalStatus", "MaritalStatusId,MaritalStatus", , "MaritalStatus")
        End If
    End Sub

    Private Sub lkDCompany_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDCompany.ButtonClick
        If e.Button.Index = 1 Then  'Refresh Data
            'Populate (Insurance) company combo box
            Call PopulateLookupDX(lkDCompany, "InsuranceCompany", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany", , "InsuranceCompany")
        End If
    End Sub

    Private Sub lkDGender_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkDGender.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkDGender.EditValue = Nothing
            lkDGender.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblSex"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkDGender, "Sex", "SexId", "LtblSex", "SexId,Sex", , "Sex")
            If mlngLookUpId > 0 Then
                lkDGender.EditValue = CInt(mlngLookUpId)
            Else
                lkDGender.EditValue = Nothing
                lkDGender.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkDMaritalStatus_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkDMaritalStatus.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkDMaritalStatus.EditValue = Nothing
            lkDMaritalStatus.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblMaritalStatus"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkDMaritalStatus, "MaritalStatus", "MaritalStatusId", "LtblMaritalStatus", "MaritalStatusId,MaritalStatus", , "MaritalStatus")
            If mlngLookUpId > 0 Then
                lkDMaritalStatus.EditValue = CInt(mlngLookUpId)
            Else
                lkDMaritalStatus.EditValue = Nothing
                lkDMaritalStatus.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkDCompany_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkDCompany.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkDCompany.EditValue = Nothing
            lkDCompany.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblInsuranceCompany"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkDCompany, "InsuranceCompany", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany", , "InsuranceCompany")
            If mlngLookUpId > 0 Then
                lkDCompany.EditValue = CInt(mlngLookUpId)
            Else
                lkDCompany.EditValue = Nothing
                lkDCompany.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub DisplayPastDetails()
        Dim Id As Integer = Val(gdvPRecords.GetRowCellValue(gdvPRecords.FocusedRowHandle, "VisitId"))
        VisitId = Id
        Dim dsTemp As DataSet = FillDataSet("Select * from tblVisits where VisitId=" & Id)
        If dsTemp.Tables(0).Rows.Count > 0 Then
            With dsTemp.Tables(0)
                dtPVisitDate.EditValue = .Rows(0).Item("VisitDate")
                lkPVisitLocation.EditValue = CInt(.Rows(0).Item("VisitLocationId"))
                txtPComplaint.Text = Trim(.Rows(0).Item("PresentingComplaint") & "")
                txtPTherapy.Text = Trim(.Rows(0).Item("Therapy") & "")
            End With
        End If
        gdvPDiagnosis.Columns.Clear()
        Call SetEditorDataColumn()
        Dim dsTempInner As DataSet
        dsTempInner = FillDataSet("SELECT tblVisitDiagnosis.VisitDiagnosisId [ID],tblVisitDiagnosis.DiagnosisId [Diagnosis], tblVisitDiagnosis.DiagnosisSeverityId,tblVisitDiagnosis.VisitId, tblVisitDiagnosis.DiagnosisDate, tblVisitDiagnosis.Active, tblVisitDiagnosis.ResolveDate FROM  tblVisitDiagnosis INNER JOIN LtblDiagnosisSeverity ON tblVisitDiagnosis.DiagnosisSeverityId = LtblDiagnosisSeverity.DiagnosisSeverityId WHERE VisitId=" & Id)
        With grdPDiagnosis
            .BeginUpdate()
            .DataSource = dsTempInner.Tables(0)
            .EndUpdate()
        End With
        gdvPDiagnosis.Columns("ID").Visible = False
        gdvPDiagnosis.Columns("VisitId").Visible = False
    End Sub

    Private Sub gdvPRecords_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvPRecords.FocusedRowChanged

        btnPastVisitNew.Text = "&New"
        btnPastVisitUpdate.Enabled = True
        mblnPchanged = False
        Call DisplayPastDetails()
    End Sub

    Private Sub gdvPDiagnosis_CellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdvPDiagnosis.CellValueChanged
        mblnPchanged = True
    End Sub

    Private Sub gdvPDiagnosis_InvalidRowException(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles gdvPDiagnosis.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub

    Private Sub gdvPDiagnosis_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvPDiagnosis.KeyDown
        If e.KeyCode = Keys.Enter Then
            If gdvPDiagnosis.FocusedColumn Is gdvPDiagnosis.Columns("ResolveDate") Then
                'dsTempInner = FillDataSet("SELECT tblVisitDiagnosis.VisitDiagnosisId [ID],tblVisitDiagnosis.DiagnosisId [Diagnosis], tblVisitDiagnosis.DiagnosisSeverityId,tblVisitDiagnosis.VisitId, tblVisitDiagnosis.DiagnosisDate, tblVisitDiagnosis.Active, tblVisitDiagnosis.ResolveDate FROM  tblVisitDiagnosis INNER JOIN LtblDiagnosisSeverity ON tblVisitDiagnosis.DiagnosisSeverityId = LtblDiagnosisSeverity.DiagnosisSeverityId WHERE VisitId=" & Id)
                If Val(Trim(gdvPDiagnosis.GetRowCellValue(gdvPDiagnosis.FocusedRowHandle, "Diagnosis") & "")) <= 0 AndAlso Val(Trim(gdvPDiagnosis.GetRowCellValue(gdvPDiagnosis.FocusedRowHandle, "Severity") & "")) <= 0 AndAlso IsDBNullOrNothing(gdvPDiagnosis.GetRowCellValue(gdvPDiagnosis.FocusedRowHandle, "DiagnosisDate")) AndAlso IsDBNullOrNothing(gdvPDiagnosis.GetRowCellValue(gdvPDiagnosis.FocusedRowHandle, "ResolveDate")) Then
                    txtPTherapy.Focus()
                End If
            End If

        End If
    End Sub

    Private Sub gdvPDiagnosis_ValidateRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles gdvPDiagnosis.ValidateRow
        Try
            Dim view As ColumnView = CType(sender, ColumnView)
            Dim colName As New GridColumn
            Dim blnError As Boolean

            If IsDBNullOrNothing(gdvPDiagnosis.GetRowCellValue(e.RowHandle, "Diagnosis").ToString) And IsDBNullOrNothing(gdvPDiagnosis.GetRowCellValue(e.RowHandle, "Severity").ToString) And IsDBNullOrNothing(gdvPDiagnosis.GetRowCellValue(e.RowHandle, "DiagnosisDate")) Then Exit Sub
            If gdvPDiagnosis.GetRowCellValue(e.RowHandle, "Diagnosis").ToString = "" Or _
                gdvPDiagnosis.GetRowCellValue(e.RowHandle, "Diagnosis").ToString = "-1" Then
                colName = view.Columns("Diagnosis") : blnError = True : view.SetColumnError(colName, "Specify Diagnosis")
            ElseIf gdvPDiagnosis.GetRowCellValue(e.RowHandle, "Severity").ToString = "" Or _
                gdvPDiagnosis.GetRowCellValue(e.RowHandle, "Severity").ToString = "-1" Then
                colName = view.Columns("Severity") : blnError = True : view.SetColumnError(colName, "Specify Diagnosis Severity")
            ElseIf gdvPDiagnosis.GetRowCellValue(e.RowHandle, "DiagnosisDate").ToString = "" Then
                colName = view.Columns("DiagnosisDate") : blnError = True : view.SetColumnError(colName, "Specify Diagnosis Date")
            End If
            If blnError = True Then view.FocusedColumn = colName : e.Valid = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub txtPComplaint_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPComplaint.KeyDown
        If e.KeyCode = Keys.Return Then
            'Call NotesFocus(txtPComplaint)
            Try

                If txtPComplaint.SelectionLength = txtPComplaint.Text.Length Then
                    txtPComplaint.EnterMoveNextControl = True
                    gdvPDiagnosis.Focus()
                    gdvPDiagnosis.FocusedColumn = gdvPDiagnosis.VisibleColumns(0)
                    gdvPDiagnosis.ShowEditor()
                    Exit Sub
                Else
                    txtPComplaint.EnterMoveNextControl = False
                End If

                Dim strTemp As String = Strings.Right(txtPComplaint.Text, 2)
                Dim strFirst2 As String = Strings.Left(strTemp, 1)
                Dim last1 As String = Strings.Right(strTemp, 1)
                If Asc(strFirst2) = 13 Then
                    If Asc(last1) = 10 Then
                        txtPComplaint.EnterMoveNextControl = True
                        gdvPDiagnosis.Focus()
                        gdvPDiagnosis.FocusedColumn = gdvPDiagnosis.VisibleColumns(0)
                        gdvPDiagnosis.ShowEditor()
                    End If
                End If

            Catch ex As Exception
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                     Reflection.MethodBase.GetCurrentMethod.Name & " Of mdlAllFunctions")
            End Try
        End If
    End Sub

    Private Sub txtPComplaint_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPComplaint.Validated
        sender.text = TrimX(sender.Text)
    End Sub

    Private Sub txtPTherapy_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPTherapy.KeyDown
        If e.KeyCode = Keys.Return Then
            Call NotesFocus(txtPTherapy)
        End If
    End Sub

    Private Sub txtPTherapy_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPTherapy.Validated
        sender.text = TrimX(sender.Text)
    End Sub
    Dim ImageId As Integer
    Private Sub DisplayImageDetails()
        Try
            ImageId = Val(gdvIRecords.GetRowCellValue(gdvIRecords.FocusedRowHandle, "ImageId"))
            Dim dsTemp As DataSet = FillDataSet("Select * from tblPatientsImages where ImageId=" & ImageId)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    'dtPVisitDate.EditValue = .Rows(0).Item("VisitDate")
                    'lkPVisitLocation.EditValue = CInt(.Rows(0).Item("VisitLocationId"))
                    'txtPComplaint.Text = Trim(.Rows(0).Item("PresentingComplaint") & "")
                    'txtPTherapy.Text = Trim(.Rows(0).Item("Therapy") & "")
                    txtIName.Text = .Rows(0).Item("ImageName")
                    txtIFullPath.Text = .Rows(0).Item("ImagePath")
                    txtIDescription.Text = .Rows(0).Item("Description")
                    txtIComments.Text = .Rows(0).Item("Comments")
                    lkIImageType.EditValue = CInt(.Rows(0).Item("ImageTypeId"))

                    If Not IsDBNullOrNothing(.Rows(0).Item("ImagePath")) Then
                        pcbImage.Image = Nothing
                        pcbImage.Image = Image.FromFile(.Rows(0).Item("ImagePath"))
                    End If
                End With
            End If

        Catch ex As Exception

        End Try
    End Sub
    Private Sub gdvIRecords_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvIRecords.FocusedRowChanged
        Call DisplayImageDetails()
        btnImageNew.Text = "&New"
        btnImageUpdate.Enabled = True
        btnImageDelete.Enabled = True
    End Sub

    Private Sub gdvIRecords_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvIRecords.GotFocus
        If gdvIRecords.RowCount > 0 Then
            Call DisplayImageDetails()
        End If

        btnImageNew.Text = "&New"
        btnImageUpdate.Enabled = True
        btnImageDelete.Enabled = True
    End Sub

    Private Sub gdvPRecords_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvPRecords.GotFocus
        If gdvPRecords.RowCount > 0 Then
            Call DisplayPastDetails()
        End If
        btnPastVisitNew.Text = "&New"
        btnPastVisitUpdate.Enabled = True
        mblnPchanged = False
    End Sub
    Dim PaymentId As Integer
    Private Sub DisplayPaymentDetails()
        Try
            PaymentId = Val(gdvAPayments.GetRowCellValue(gdvAPayments.FocusedRowHandle, "PaymentId"))
            Dim dsTemp As DataSet = FillDataSet("Select * from tblPayment where PaymentId=" & PaymentId)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    lkAPaymentType.EditValue = CInt(.Rows(0).Item("PaymentTypeId"))
                    lkASelectPractice.EditValue = CInt(.Rows(0).Item("PracticeId"))
                    txtAPayment.Text = Val(.Rows(0).Item("Payment"))
                    dtPaymentDate.EditValue = Format(.Rows(0).Item("PaymentDate"), gstrDtFormat)
                    If IsDBNullOrNothing(.Rows(0).Item("InsuranceCompanyId")) Then
                        lkAInsuranceCompany.EditValue = Nothing
                    Else
                        lkAInsuranceCompany.EditValue = CInt(.Rows(0).Item("InsuranceCompanyId"))
                    End If

                    Dim dsTempInner As DataSet = FillDataSet("Select * from tblCheck where CheckId=" & Val(.Rows(0).Item("CheckId")))
                    If dsTempInner.Tables(0).Rows.Count > 0 Then
                        txtAChqCrdtBank.Text = dsTempInner.Tables(0).Rows(0).Item("BankName")
                        txtAChqCrdtDrawer.Text = dsTempInner.Tables(0).Rows(0).Item("Drawer")
                        txtAChqCrdtNo.Text = dsTempInner.Tables(0).Rows(0).Item("Number")
                        dtAChqCrdtDate.EditValue = Format(dsTempInner.Tables(0).Rows(0).Item("CheckDate"), gstrDtFormat)
                    End If
                End With
            End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub gdvAPayments_FocusedRowChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvAPayments.FocusedRowChanged
        Call DisplayPaymentDetails()
        btnAccountNew.Text = "&New"
        btnAccountUpdate.Enabled = True
        btnAccountDelete.Enabled = True
        dtPaymentDate.Enabled = True
    End Sub

    Private Sub gdvAPayments_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvAPayments.GotFocus
        If gdvAPayments.RowCount > 0 Then
            Call DisplayPaymentDetails()
        End If
        btnAccountNew.Text = "&New"
        btnAccountUpdate.Enabled = True
        btnAccountDelete.Enabled = True
    End Sub

    Private Sub lkPVisitLocation_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkPVisitLocation.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkPVisitLocation, "VisitLocation", "VisitLocationId", "LtblVisitLocation", "VisitLocationId, VisitLocation", , "VisitLocation")
        End If
    End Sub

    Private Sub lkPVisitLocation_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkPVisitLocation.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkPVisitLocation.EditValue = Nothing
            lkPVisitLocation.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblVisitLocation"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkPVisitLocation, "VisitLocation", "VisitLocationId", "LtblVisitLocation", "VisitLocationId, VisitLocation", , "VisitLocation")
            If mlngLookUpId > 0 Then
                lkPVisitLocation.EditValue = CInt(mlngLookUpId)
            Else
                lkPVisitLocation.EditValue = Nothing
                lkPVisitLocation.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkIImageType_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkIImageType.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkIImageType, "ImageType", "ImageTypeId", "LtblImageType", "ImageTypeId,ImageType", , "ImageType")
        End If
    End Sub

    Private Sub lkIImageType_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkIImageType.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkIImageType.EditValue = Nothing
            lkIImageType.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblImageType"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkIImageType, "ImageType", "ImageTypeId", "LtblImageType", "ImageTypeId,ImageType", , "ImageType")
            If mlngLookUpId > 0 Then
                lkIImageType.EditValue = CInt(mlngLookUpId)
            Else
                lkIImageType.EditValue = Nothing
                lkIImageType.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkAPaymentType_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkAPaymentType.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkAPaymentType.EditValue = Nothing
            lkAPaymentType.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblPaymentType"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkAPaymentType, "PaymentType", "PaymentTypeId", "LtblPaymentType", "PaymentTypeId,PaymentType", , "PaymentType")
            If mlngLookUpId > 0 Then
                lkAPaymentType.EditValue = CInt(mlngLookUpId)
            Else
                lkAPaymentType.EditValue = Nothing
                lkAPaymentType.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkAInsuranceCompany_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkAInsuranceCompany.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkDCompany, "InsuranceCompany", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany", , "InsuranceCompany")
        End If
    End Sub

    Private Sub lkAInsuranceCompany_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkAInsuranceCompany.EditValueChanged, lkASelectPractice.EditValueChanged
        mblnAChanged = True
    End Sub

    Private Sub lkAInsuranceCompany_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkAInsuranceCompany.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkAInsuranceCompany.EditValue = Nothing
            lkAInsuranceCompany.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblInsuranceCompany"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkDCompany, "InsuranceCompany", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany", , "InsuranceCompany")
            If mlngLookUpId > 0 Then
                lkAInsuranceCompany.EditValue = CInt(mlngLookUpId)
            Else
                lkAInsuranceCompany.EditValue = Nothing
                lkAInsuranceCompany.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub lkASelectPractice_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkASelectPractice.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkASelectPractice, "Name", "PracticeId", "tblPracticeInfo JOIN vwUserDetails ON tblPracticeInfo.UserId=vwUserDetails.UserId", "PracticeId,FullName [Name]", , "[Name]")
        End If
    End Sub

    Private Sub txtIComments_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtIComments.KeyDown
        If e.KeyCode = Keys.Return Then
            Call NotesFocus(txtIComments)
        End If
    End Sub

    Private Sub txtIDescription_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtIDescription.KeyDown
        If e.KeyCode = Keys.Return Then
            Call NotesFocus(txtIDescription)
        End If
    End Sub

    Private Sub txtDFirstName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDFirstName.TextChanged, txtDStreetAddress2.TextChanged, txtDStreetAddress1.TextChanged, txtDMiddleName.TextChanged, txtDLastName.TextChanged, txtDWorkPhone.TextChanged, txtDPolicyNo.TextChanged, txtDOccupation.TextChanged, txtDKinPhone.TextChanged, txtDKinOccupation.TextChanged, txtDKinName.TextChanged, txtDInsuredName.TextChanged, txtDHomePhone.TextChanged, cboTitle.SelectedIndexChanged
        mblnChanged = True
    End Sub

    Private Sub dtPVisitDate_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtPVisitDate.EditValueChanged
        mblnPchanged = True
    End Sub

    Private Sub gdvVaccinationHistory_CellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdvVaccinationHistory.CellValueChanged
        mblnVChanged = True
    End Sub

    Private Sub txtIComments_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtIComments.Validated
        sender.text = TrimX(sender.Text)
    End Sub

    Private Sub txtIDescription_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtIDescription.Validated
        sender.text = TrimX(sender.text)
    End Sub

    Private Sub gdvVaccinationHistory_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvVaccinationHistory.KeyDown
        If e.KeyCode = Keys.Enter Then
            If gdvVaccinationHistory.FocusedColumn Is gdvVaccinationHistory.Columns("Vaccine") Then
                If IsDBNullOrNothing(gdvVaccinationHistory.GetRowCellValue(gdvVaccinationHistory.FocusedRowHandle, "Date")) AndAlso Val(Trim(gdvVaccinationHistory.GetRowCellValue(gdvVaccinationHistory.FocusedRowHandle, "Vaccine") & "")) <= 0 Then
                    btnVaccinationSave.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub chkDecreased_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkDecreased.CheckedChanged
        mblnChanged = True
        If chkDecreased.Checked = True Then
            dtDeathDate.Enabled = True
            lkCauseOfDeath.Enabled = True
            dtDeathDate.EditValue = Format(Today, gstrDtFormat)
        Else
            dtDeathDate.Enabled = False
            lkCauseOfDeath.Enabled = False
            dtDeathDate.EditValue = Nothing
        End If
    End Sub

    Private Sub lkCauseOfDeath_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkCauseOfDeath.ButtonClick
        If e.Button.Index = 1 Then
            'Populate Cause of Death Lookup
            Call PopulateLookupDX(lkCauseOfDeath, "Cause Of Death", "CauseId", "LtblCauseOfDeath", "CauseId,Cause [Cause Of Death]", , "Cause")
        End If
    End Sub

    Private Sub lkCauseOfDeath_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkCauseOfDeath.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkCauseOfDeath.EditValue = Nothing
            lkCauseOfDeath.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblCauseOfDeath"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(lkCauseOfDeath, "Cause Of Death", "CauseId", "LtblCauseOfDeath", "CauseId,Cause [Cause Of Death]", , "Cause")
            If mlngLookUpId > 0 Then
                lkCauseOfDeath.EditValue = CInt(mlngLookUpId)
            Else
                lkCauseOfDeath.EditValue = Nothing
                lkCauseOfDeath.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub dtDeathDate_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtDeathDate.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub lkCauseOfDeath_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkCauseOfDeath.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub btnEnterPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPayment.Click
        Dim frmTempChargesLogin As New frmChargesPaymentLogin
        With frmTempChargesLogin
            '.MdiParent = Me.ParentForm
            .ShowInTaskbar = False
            .ShowDialog()
            'Me.Dispose()
            'GC.Collect()
        End With
        If gintPaymentUserID > 0 Then
            btnEnterPayment.Enabled = False
            grbPayments.Enabled = True
            grbButtons.Enabled = True
            lkAPaymentType.Focus()
        Else
            btnEnterPayment.Enabled = True
            grbPayments.Enabled = False
            grbButtons.Enabled = False
        End If
        'If mblnPopulateAccount = False Then
        '    xtcMain.SelectedTabPage = xtpDemographics
        'Else
        '    FillAccountTab()
        '    xtcMain.SelectedTabPage = xtpAccount
        '    IsThisTabPopulated(xtcMain.SelectedTabPageIndex) = True
        'End If
    End Sub

    Private Sub gdvVaccinationHistory_FocusedRowChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvVaccinationHistory.FocusedRowChanged
        '' ''Dim View As DevExpress.XtraGrid.Views.Grid.GridView
        '' ''View = gdvVaccinationHistory
        '' ''Dim strtemp As String = ""
        '' ''If View.IsLastVisibleRow Then
        '' ''    Dim currentRow As Integer
        '' ''    currentRow = View.FocusedRowHandle
        '' ''    'View.AddNewRow()
        '' ''    If View.RowCount > 1 Then
        '' ''        View.SetRowCellValue(View.FocusedRowHandle, "Date", gdvVaccinationHistory.GetRowCellValue(gdvVaccinationHistory.RowCount, "Date"))

        '' ''    Else
        '' ''        View.SetRowCellValue(View.FocusedRowHandle, "Date", Format(gdtCurrentDate, gstrDtFormat))
        '' ''    End If
        '' ''    View.UpdateCurrentRow()
        '' ''    'View.MakeRowVisible(gdvSerialVehicle.FocusedRowHandle, True)
        '' ''    View.ShowEditor()
        '' ''    View.FocusedColumn = View.VisibleColumns(0)
        '' ''End If
    End Sub

    Private Sub lkDCountry_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkDCountry.EditValueChanged, lkDMaritalStatus.EditValueChanged, lkDGender.EditValueChanged, lkDCompany.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub lkPVisitLocation_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkPVisitLocation.EditValueChanged
        mblnPchanged = True
    End Sub

    Private Sub txtPComplaint_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPComplaint.TextChanged, txtPTherapy.TextChanged
        mblnPchanged = True
    End Sub

    Private Sub txtIName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtIName.TextChanged, txtIFullPath.TextChanged, txtIDescription.TextChanged, txtIComments.TextChanged
        mblnIChanged = True
    End Sub

    Private Sub lkIImageType_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkIImageType.EditValueChanged
        mblnIChanged = True
    End Sub


    Private Sub dtANextAppointment_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtANextAppointment.EditValueChanged, dtAChqCrdtDate.EditValueChanged
        mblnAChanged = True
    End Sub

    Private Sub gdvACharges_CellValueChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdvACharges.CellValueChanged
        mblnAChanged = True
    End Sub
    Private Sub btnNurseNotes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNurseNotes.Click
        Dim Id As Integer = Val(strRecordID("tblVisits", "max(VisitId)", "PatientId=" & PatientId & " and VisitDate between '" & Format(DateTime.Now, gstrDtFormat & " 00:01") & "' and '" & Format(DateTime.Now, gstrDtFormat & " 23:59") & "'"))
        If Id <= 0 Then
            MessageBox.Show("Patient is not registered today. So you cannot enter Notes", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If
        Dim frmTempNurseNote As New frmNurseNote(Id)
        With frmTempNurseNote
            .MdiParent = Me.ParentForm
            .Show()
        End With
        'frmTempForm = New frmNurseNote(gdvRecords.GetFocusedRowCellValue("VisitId"))
    End Sub

    Private Sub btnDoctorNotes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDoctorNotes.Click
        Dim Id As Integer = Val(strRecordID("tblVisits", "max(VisitId)", "PatientId=" & PatientId & " and VisitDate between '" & Format(DateTime.Now, gstrDtFormat & " 00:01") & "' and '" & Format(DateTime.Now, gstrDtFormat & " 23:59") & "'"))
        If Id <= 0 Then
            MessageBox.Show("Patient is not registered today. So you cannot enter Notes", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If
        Dim frmTempDoctorsNote As New frmDoctorsNote
        With frmTempDoctorsNote
            .MdiParent = Me.ParentForm
            .VisitId = Id
            .Show()
        End With
    End Sub
End Class
